package com.elinkway.infinitemovies.ui.activity;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.elinkway.infinitemovies.adaction.CommonAdActionHandle;
import com.elinkway.infinitemovies.adapter.DownLoadEpisodePagerAdapter;
import com.elinkway.infinitemovies.adapter.DownloadEpisodePlayAdapter;
import com.elinkway.infinitemovies.adapter.EpisodeGridAdapter;
import com.elinkway.infinitemovies.adapter.EpisodeListAdapter;
import com.elinkway.infinitemovies.adapter.EpisodePagerAdapter;
import com.elinkway.infinitemovies.adapter.EpisodePlayAdapter;
import com.elinkway.infinitemovies.adapter.PlaySrcPopupListAdapter;
import com.elinkway.infinitemovies.adapter.RelativeListAdapter;
import com.elinkway.infinitemovies.adapter.RelativeListAdapter.RelativItemClickListener;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.async.RequestRelationsTask;
import com.elinkway.infinitemovies.async.RequestResultListener;
import com.elinkway.infinitemovies.bean.Episode;
import com.elinkway.infinitemovies.bean.Favorite;
import com.elinkway.infinitemovies.bean.HzPayload;
import com.elinkway.infinitemovies.bean.IsFavoriteBean;
import com.elinkway.infinitemovies.bean.JumpData;
import com.elinkway.infinitemovies.bean.NewAdDataBean;
import com.elinkway.infinitemovies.bean.Payload;
import com.elinkway.infinitemovies.bean.PlayData;
import com.elinkway.infinitemovies.bean.PlayRecord;
import com.elinkway.infinitemovies.bean.PlaySrcBean;
import com.elinkway.infinitemovies.bean.PlaySrcList;
import com.elinkway.infinitemovies.bean.PlayStatusReporter;
import com.elinkway.infinitemovies.bean.RelationAlbum;
import com.elinkway.infinitemovies.bean.RelationList;
import com.elinkway.infinitemovies.bean.SDKPayload;
import com.elinkway.infinitemovies.bean.ServerPayload;
import com.elinkway.infinitemovies.bean.TtPayload;
import com.elinkway.infinitemovies.bean.UMengReport;
import com.elinkway.infinitemovies.bean.VideoDataBean;
import com.elinkway.infinitemovies.bean.XfPayload;
import com.elinkway.infinitemovies.bean.YzPayload;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.bigdata.BigDataLaunchQuitActionTask;
import com.elinkway.infinitemovies.bigdata.BigDataPlayReporter;
import com.elinkway.infinitemovies.bigdata.BigDataStats;
import com.elinkway.infinitemovies.bigdata.BigDataUtils;
import com.elinkway.infinitemovies.bigdata.RealDataApi;
import com.elinkway.infinitemovies.config.LogoImageLoader;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.dao.FavoriteDao;
import com.elinkway.infinitemovies.dao.PlayRecordDao;
import com.elinkway.infinitemovies.dao.PreferencesManager;
import com.elinkway.infinitemovies.download.Constants;
import com.elinkway.infinitemovies.download.ContainSizeManager;
import com.elinkway.infinitemovies.download.DownloadEntity;
import com.elinkway.infinitemovies.download.DownloadHelper;
import com.elinkway.infinitemovies.download.DownloadJob;
import com.elinkway.infinitemovies.download.DownloadManager;
import com.elinkway.infinitemovies.download.DownloadObserver;
import com.elinkway.infinitemovies.download.DownloadUtils;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.VideoDetailParser;
import com.elinkway.infinitemovies.http.parser.VideoListParser;
import com.elinkway.infinitemovies.http.requestInterface.RequestCommonInterface;
import com.elinkway.infinitemovies.http.requesttask.ReportPlayStatusTask;
import com.elinkway.infinitemovies.http.requesttask.RequestAdTask;
import com.elinkway.infinitemovies.http.requesttask.RequestAddFavoriteTask;
import com.elinkway.infinitemovies.http.requesttask.RequestDoPlayRecordTask;
import com.elinkway.infinitemovies.http.requesttask.RequestIsAddFavoriteTask;
import com.elinkway.infinitemovies.http.requesttask.RequestRemoveFavoriteTask;
import com.elinkway.infinitemovies.listener.NetClarityListener;
import com.elinkway.infinitemovies.listener.PlayCallBackListener;
import com.elinkway.infinitemovies.push.PushStatsPoster;
import com.elinkway.infinitemovies.selfdata.AdRequestStatis;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.SelfDataConstant;
import com.elinkway.infinitemovies.selfdata.bean.LoginDataRecord;
import com.elinkway.infinitemovies.selfdata.bean.MyDataRecord;
import com.elinkway.infinitemovies.selfdata.bean.PlayDataRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.shakead.ShakeAd;
import com.elinkway.infinitemovies.share.SharePopupWindow;
import com.elinkway.infinitemovies.ui.activity.play.PlayActivityFroWebView;
import com.elinkway.infinitemovies.ui.activity.play.PlayActivitySelfOwn;
import com.elinkway.infinitemovies.ui.activity.play.PlayMediaController;
import com.elinkway.infinitemovies.ui.activity.play.PlayerUtils;
import com.elinkway.infinitemovies.utils.ACache;
import com.elinkway.infinitemovies.utils.DialogUtil;
import com.elinkway.infinitemovies.utils.LiteAppManager;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.MoviesUtils;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.elinkway.infinitemovies.utils.SharePreferenceManager;
import com.elinkway.infinitemovies.utils.StringUtil;
import com.elinkway.infinitemovies.utils.ToastUtil;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.elinkway.infinitemovies.view.BaiduNativeAdView;
import com.elinkway.infinitemovies.view.DefinitionManager;
import com.elinkway.infinitemovies.view.GdtNativeAdView;
import com.elinkway.infinitemovies.view.HzPayAdView;
import com.elinkway.infinitemovies.view.IntroduceView;
import com.elinkway.infinitemovies.view.LoginPopupWindow;
import com.elinkway.infinitemovies.view.MarqueeView;
import com.elinkway.infinitemovies.view.ServerNativeAdView;
import com.elinkway.infinitemovies.view.TtPayAdView;
import com.elinkway.infinitemovies.view.XfPayAdView;
import com.elinkway.infinitemovies.view.YzPayAdView;
import com.flyco.tablayout.SlidingTabLayout;
import com.le123.ysdq.R;
import com.lvideo.http.bean.LVideoDataHull;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.recyclerlayout.refresh.MyMessageEvent;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.elinkway.infinitemovies.application.MoviesApplication.START_FROM_NOTIFICATION;
import static com.le123.ysdq.R.id.iv_video_download;
import static com.le123.ysdq.R.id.rl_score;
import static com.le123.ysdq.R.id.tv_area;

public class VideoDetailActivity extends BaseActionBarActivity implements OnClickListener,
        DownloadObserver, RequestCommonInterface, PlayCallBackListener, NetClarityListener, RelativItemClickListener {

    public static final String TAG = "VideoDgetailActivity";
    private FrameLayout mContainer;
    private boolean isADload;
    private NewAdDataBean mDetailAdData;

    public VideoDataBean video;
    private ScrollView scrollView;
    private RelativeLayout dialogBgRl;
    private PopupWindow mCurrentPopup;

    private ImageView playIv;
    private ImageView downloadIv;
    private ImageView offlineIv;
    private ImageView poster;
    private ImageView mVideoBgIv;
    private RelativeLayout playDetailContentRl;
    private TextView mYearTxt;
    private TextView mRating;
    private TextView mCategoryTxt;
    private TextView mAreaTxt;

    private TextView year;
    private TextView director;
    private TextView starring;
    private TextView score;
    private PopupWindow mEpisodePopup;
    private EpisodePagerAdapter mEpisodePagerAdapter;
    private DownLoadEpisodePagerAdapter mDownLoadEpisodePagerAdapter;

    private PopupWindow mDownloadPopup;

//    private PullToRefreshGridView mDownloadPopupGridview;
//    private PullToRefreshListView mDownloadPopupListview;
//    private DownLoadGridAdapter downloadPopupGridAdapter;
//    private DownLoadListAdapter downloadPopupListAdapter;

    private PopupWindow mIntroPopup;
    private TextView introPopupTv;
    private PopupWindow mPlaySrcPopup;
    private ListView mSrcListview;
    private PlaySrcPopupListAdapter popupAdapter;
    private RelativeLayout playSrcLl;
    private ImageView playSrcIconIv;
    private TextView playSrcTips;

    private TextView playSrcTxtTv;
    private RelativeLayout introduceMoreTv;
    private RelativeLayout lineAdTop; // 广告上面的横线
    private LinearLayout episodeDataLl;
    private TextView episodeTitleTv;
    private TextView moreEpisodeTv;
    private RelativeLayout allEpisode;
    private RecyclerView episodeListview;
    private EpisodeGridAdapter mEpisodeGridAdapter;
    //    private RecyclerView varietyListview;
    private EpisodeListAdapter mEpisodeListAdapter;

    private LinearLayout relativeRecommendLl;
    private RelativeLayout lineRelativeTop; // 猜你喜欢上面的横线
    private RecyclerView relativeListview;
    private boolean isFavorite = false;
    private boolean mIsWifiTo3GFlag;
    private boolean isShareGuideGone = false;
    private Resources res;
    private String videoTitle;
    private String aid;
    private String porder = "0";
    private String mThemeId;

    private final String NEED_REPORT = "1";
    private final String POINT = ".";
    private final String DEFAULT_POINT_VAULE = ".0";

    private final static int PORTRAIT = 0;

    private final static int LANDSCAPE = 1;

    private final static int LANDSCAPE_REVERSE = 2;

    private final static int SCREEN_ROTATION_ON = 1;

    private static final int FULL_SCREEN_LAND_MIN_DEGREE = 45;

    private static final int FULL_SCREEN_LANDSCAPE_MAX_DEGREE = 180;

    private static final int FULL_SCREEN_REVERSE_MIN_DEGREE = 315;

    private static final int FULL_SCREEN_LAND_REVERSE_MAX_DEGREE = 340;

    private static final int PLAY_CONTROL_ON_RESUME = FULL_SCREEN_LAND_REVERSE_MAX_DEGREE + 1; // 延长获取锁屏状态


    private RequestVideoDataTask requestTask;
    private View loading;
    private ImageView mLoadingIv;
    private AnimationDrawable animationDrawable;
    private View loading_failed;
    private View noMovieLayout;
    private RelativeLayout mShareGuideView;
    private Button btnRefresh;
    private FavoriteDao favoriteDao;
    public PlaySrcList mPlaySrcList;
    private RequestPlaySrcDetailTask requestPlaySrcDetail;
    private RequestVideoListTask mRequestVideoListTask;
    private PlayRecord playRecord;
    private PlayRecordDao playRecordDao;
    private Dialog mProgressDialog;
    private ACache mCache;
    private RelativeLayout containerLayout;
    private TextView mDefinition_fluency;
    private TextView mDefinition_common;
    private TextView mDefinition_highclear;
    private TextView mDefinition_super;
    private TextView mMoveDefinition_fluency;
    private TextView mMoveDefinition_common;
    private TextView mMoveDefinition_highclear;
    private TextView mMoveDefinition_super;
    private View downloadPopupMoveView;
    public boolean isBackToForeGround = false;
    /**
     * 下载清晰度
     */
    private String mdefaultClarity = PlayerUtils.PLS_MP4_720p_db;
    private String mOutsiteClarity = MoviesConstant.SUPER;
    private int addTime;
    /**
     * 分享对象
     */
    private SharePopupWindow mShareWindow;

    /**
     * 分享PopupWindow
     */
    private PopupWindow mSharePopupWindow;

    /**
     * 登录popWindow
     */
    private LoginPopupWindow mLoginPopupWindow;
    /**
     * 登录PopupWindow
     */
    private PopupWindow mLoginPw;

    private SharedPreferences mLoginSp;
//    private SharedPreferences mClaritySp;

    private TextView downloadedNumTv;
    private TextView downloadedNumMovTv;


    private static final int DISSMISS_SHAREGUIDE_PAGE = 0;
    private static final long SHAREGUIDE_DISSMISS_TIME = 3000;
    public ContainSizeManager mSizeManager;
    private DisplayImageOptions displayoptions = new DisplayImageOptions.Builder()
            .resetViewBeforeLoading(false).cacheInMemory(true)
            .cacheOnDisc(true).bitmapConfig(Bitmap.Config.ARGB_8888).build();

    private RequestAddFavoriteTask mRequestAddFavoriteTask;
    private RequestRemoveFavoriteTask mRequestRemoveFavoriteTask;
    private RequestIsAddFavoriteTask mRequestIsAddFavoriteTask;

    // 网络变化广播接收
    private NetworkCheckReceiver mCheckReceiver;
    // 获取是否允许3g下载的用户选择数据
    private SettingManage mSettingManage;
    private SharedPreferences mSettingSharePreference;
    private Editor mSettingPreferenceEditor;
    private DownloadManager downLoadManager;
    private int pageIndex = 1;
    private int pageSize = 100;
    private RelativeLayout mReportImageView;
    private String mStartFrom;
    private String mIsDownload;
    private String mOpenWay;
    private String mLastFromClass;

    private RelationList mRelativeList;

    private RelativeListAdapter mRelativeAdapter;

    private PopupWindow mPopupWindow;

    private View mPopView;

    private LinearLayout mPlayPopLinearLayout;

    private ImageView mPopPlayImageView;

    private ImageView mPopImageView;

    private ImageView mWebPageImageView;

    private ImageView mWebPageImageViewInPop;

    private Map<String, String> bdDownloadDataMap;

    public FrameLayout mVideoPlayerLayout;

    private PlayMediaController mPlayMediaController;

    public Boolean fromBackground = false;

    private TextView mTitleView;


    private ImageView mFavoriteImage;

    private ImageView mDownloadImage;

    private ImageView mShareImage;

    private TextView mRecommendAll;

//    private LinearLayout mDownloadHeader;

    private PlayData mPlayData;

    private long mCurrentTime;

    private LinearLayout mPlayStatus;

    private TextView mPlayerStatus;

    private TextView mPlayerStatusImage;

    private RelativeLayout mPlayerControl;

    private Boolean mCanPlayDirectly = true;

    private ImageView mPlayBackButton;

    private LinearLayout mlyBtnPlayWeb; // 爱奇艺播放按钮

    private boolean mIsHalfScreen = true;

    private String mCurrentSite;    //当前的站点源，用于请求websitepage接口。

    private OrientationEventListener mOrientationListener; // 屏幕方向改变监听器

    private int mCurrentPlayPisiotion;

    private PlayStatusReporter mPlayStatusReport;

    private BigDataPlayReporter bigDataPlayReporter;

    private int position = -1;

    private IntroduceView introduceview;
    private ImageView mMoreIcon;

    public void setWifiTo3GFlag(boolean flag) {
        mIsWifiTo3GFlag = flag;
    }

    public boolean getWifiTo3GFlag() {
        return mIsWifiTo3GFlag;
    }

    // 播放记录
    private PlayRecordDao mPlayRecordDao;

    private SharedPreferences mLoginSP;

    private SlidingTabLayout mTabs;
    private SlidingTabLayout mDownLoadTabs;

    private ViewPager mViewPager;
    private ViewPager mDownLoadViewPager;

    public ArrayList<String> mEpisodePagerList;

    private RelativeLayout mCurrentRelative;

    private RelativeLayout mRelativeLayout;
    private RelativeLayout mDownLoadRelativeLayout;

    private ArrayList<ArrayList<Episode>> mEpisodeList;

    private HashMap<String, ArrayList<Episode>> mEpisodeMapList;

    private String mCurrentPlayingPorder = "";
    private String mCurrentDownLoadingPorder = "";

    private EpisodePlayAdapter mCurrentEpisodePlayAdapter;
    private DownloadEpisodePlayAdapter mDownLoadCurrentEpisodePlayAdapter;
    private RelativeLayout marqueeContaner;
    private ImageView marqueeIcon;
    private MarqueeView marqueeView;
    private TextView marqueeMore;
    private long lastRequestMoreTime;

    private long currentRequestMoreTime;

    private boolean lastRequestMoreSuccessed = true;

    private boolean mIsLoading;
    private String seid;
    private String bucket;
    private boolean mClickInPort = false;
    private boolean mClickInLand = false;

    private LinearLayout mRetryLinearLayout;
    private DetailRelativeMovieTask mDetailRelativeMovieTask;
    private RequestAdTask mRequestAdTask;
    private SimpleRequestVideoListTask mSimpleRequestVideoListTask;
    private AdRequestResultListener mAdRequestResultListener;
    private RequestAdTask mRequestAdRecomTask; // 推荐广告位请求
    private AdRecomRequestResultListener mAdRecomRequestResultListener; // 推荐广告位监听
    private NewAdDataBean beanRecomFirst; // 推荐列表第一个广告位数据
    private NewAdDataBean beanRecomSecond; // 推荐列表第二个广告位数据
    private boolean isFirstRequestRecomAd = false; // 是否在推荐列表加载后请求了推荐广告


    private boolean mIsPlayingProcess;

    private ShakeAd mShakeAd;
    private int mNavigationBarColor;
    private boolean hadFullScreen;
    private BaiduNativeAdView mBaiduAd;
    // 反作弊埋点
    private MyDataRecord myDataRecord;
    private String showType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setActionBarActivityClassName(TAG);
        if (Utils.isMonkeyRunning()) {
            finish();
            return;
        }
        MoviesConstant.isRefreshMyFragment = true;
        setContentView(R.layout.activity_videodetail_layout);
        initActionBar();
        containerLayout = (RelativeLayout) findViewById(R.id.container);
        registerCheckNetwork();
        Bundle bundle = getIntent().getExtras();
        mStartFrom = getIntent().getStringExtra("from");
        final String FROM_PUSH_KEY = "from_push_notification";
        BigDataLaunchQuitActionTask launchStatsTask = new BigDataLaunchQuitActionTask();
        if (null != bundle && bundle.containsKey(FROM_PUSH_KEY)
                && bundle.getBoolean(FROM_PUSH_KEY)) {
            launchStatsTask.setAcode(BigDataConstants.ACODE_LAUNCH)
                    .setApType(BigDataConstants.AP_LAUNCH_PUSH)
                    .setNT(BigDataUtils.getNetType(this)).onEventStart();
        }
        mCache = ACache.get(this);
        res = getResources();
        JumpData jumpData = (JumpData) getIntent().getSerializableExtra(
                Utils.ALBUM_DATA);
        if (jumpData != null) {
            seid = jumpData.getSeid();
            bucket = jumpData.getBucket();
            aid = jumpData.getAid();
            porder = jumpData.getPorder();
            mCurrentPlayingPorder = porder;
            currentPageId = BigDataConstants.PGV_CURRENT_ID_DETAIL + aid;
            mThemeId = jumpData.getThemeid();
            videoTitle = jumpData.getName();
        }
        initPlayPopupWindow();
        initView();
        mTitleView.setText(videoTitle);
        TextPaint tp = mTitleView.getPaint();
        tp.setFakeBoldText(true);
        initViewPager();
        initLoading();
        LogUtils.e("video_detail", "aid: " + aid);

        requestTask = new RequestVideoDataTask(MoviesApplication.getInstance(), mStartFrom);
        requestTask.start();
        mEpisodeMapList = new HashMap<>();
        LogUtils.e(TAG, "on reResume request addata !!!!prepare!!!!");

        // 推送跳转友盟数据上报
        PushStatsPoster.postPushClickStats(getIntent().getExtras(),
                UmengEventPoster.PUSH_TYPE_ALBUM);

        initSharePopupWindow();
        initLoginPopupWindow();

        mSizeManager = new ContainSizeManager(this);

        MoviesApplication.getInstance().setTopActivity(this);

        MoviesApplication.getInstance().setVideoDetailActivity(this);

        downLoadManager = MoviesApplication.getInstance().getDownloadManager();

        mSettingManage = new SettingManage(this);
        mSettingSharePreference = getSharedPreferences(
                SettingManage.SETTING_RELATIVE_SHAREPREFERENCE,
                Context.MODE_PRIVATE);
        mSettingPreferenceEditor = mSettingSharePreference.edit();
        if (null != bundle && bundle.containsKey(FROM_PUSH_KEY)
                && bundle.getBoolean(FROM_PUSH_KEY)) {
            launchStatsTask.setAR(BigDataConstants.AR_SUCCESS).onEventStop(
                    false);
            BigDataStats.post(launchStatsTask);
        }
//        position = -1;
//        showShareGuidePage();
        mLoginSP = this.getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE);
        mPlayRecordDao = new PlayRecordDao(this);
        mShakeAd = new ShakeAd(this, findViewById(R.id.shake_ad));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mNavigationBarColor = getWindow().getNavigationBarColor();
        }
        mShakeAd.requestShakeAd(MoviesHttpApi.DETAIL_SHAKE);
        // 展现埋点
        myDataRecord = new MyDataRecord();
        myDataRecord.setCur_url("half_screen");
        myDataRecord.setAcode("41");
        myDataRecord.setAid(aid);
        RealmDaoManager.addMyDataRecord(myDataRecord);
    }

    @Override
    protected void initActionBar() {
        super.initActionBar();
        mActionBar.hide();
    }
    private void umengServerShow() {
        HashMap<String, String> propertyMap = new HashMap<>();
        propertyMap.put("position", "detailact");
        UmengEventPoster.doPost(UmengEventPoster.SERVER_SHOW, propertyMap);
    }

    private void umengServerClick() {
        HashMap<String, String> propertyMap = new HashMap<>();
        propertyMap.put("position", "detailact");
        UmengEventPoster.doPost(UmengEventPoster.SERVER_CLICK, propertyMap);
    }

    private void showMarqueeView(NewAdDataBean result) {
        if (null == result) {
            return;
        }
        final ServerPayload serverPayload = (ServerPayload) result.payload;
        if (null == serverPayload) {
            return;
        }

        if (!MoviesUtils.isProductKuaiKan()) {
            return;
        }

        String[] marqueenContent = serverPayload.desc.split("\n");
        marqueeContaner = (RelativeLayout) findViewById(R.id.marqueeContaner);
        marqueeIcon = (ImageView) findViewById(R.id.marqueeIcon);
        marqueeView = (MarqueeView) findViewById(R.id.marqueeView);
        marqueeMore = (TextView) findViewById(R.id.marqueeMore);
        marqueeMore.setText(serverPayload.triggerText);
        marqueeMore.setTextColor(Color.parseColor(serverPayload.triggerColor));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            marqueeMore.setLetterSpacing(Float.valueOf(serverPayload.triggerTextSpace));
        }

        umengServerShow();
        marqueeContaner.setVisibility(View.VISIBLE);
        ImageLoader.getInstance().displayImage(serverPayload.pic, marqueeIcon);
        List<String> info = new ArrayList<>();
        for (int i = 0; i < marqueenContent.length; i++) {
            info.add(marqueenContent[i]);
        }
        marqueeView.startWithList(info);
        marqueeContaner.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                umengServerClick();
                CommonAdActionHandle.getInstance().doServerAd(VideoDetailActivity.this, serverPayload, MoviesHttpApi.DETAIL_MARQUE);
            }
        });
        marqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, TextView textView) {
                umengServerClick();
                CommonAdActionHandle.getInstance().doServerAd(VideoDetailActivity.this, serverPayload, MoviesHttpApi.DETAIL_MARQUE);
            }
        });
    }

    private void requestMarqueenAd() {
        if (MoviesUtils.isProductKuaiKan()) {
            new RequestAdTask(MoviesApplication
                    .getInstance(), MoviesHttpApi.DETAIL_MARQUE, new RequestResultListener<NewAdDataBean>() {

                @Override
                public boolean onRequestFailed() {
                    LogUtils.e(TAG, "!!!!!!!!!!!!!!请求广告数据失败!!!!!!!!!!!!!!");
                    return false;
                }

                @Override
                public void onRequestSuccess(int updateId, NewAdDataBean result) {
                    LogUtils.e(TAG, "!!!!!!!!!!!!!!AdDataBean：" + result);
                    if (result != null) {
                        showMarqueeView(result);
                        LogUtils.e(TAG, "!!!!请求广告数据成功!!!!");
                    }
                }

                @Override
                public void onPreRequest() {

                }
            }).start();
        }
    }

    public void initPlayPopupWindow() {
        mPopView = UIs.inflate(this, R.layout.play_pop_layout, null);
        TranslateAnimation animTopIn = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, -0.5f,
                Animation.RELATIVE_TO_SELF, 0.0f);
        animTopIn.setDuration(300);
        mPopView.setAnimation(animTopIn);
        mPopupWindow = new PopupWindow(mPopView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setFocusable(false);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mPopImageView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mPopImageView.setClickable(true);
                    }
                }, 200);
            }
        });
        mWebPageImageViewInPop = (ImageView) mPopView.findViewById(R.id.iv_popup_webpage_play);
    }

    public void showPopWindow(View view) {
        if (mPopupWindow == null) {
            return;
        }
        mPopupWindow.setAnimationStyle(R.style.popwin_anim_style);
        if (!this.isFinishing()) {
            int[] array = new int[2];
            view.getLocationInWindow(array);
            int x = array[0];
            int y = array[1] + view.getHeight() + UIs.dipToPx(2);
            mPopupWindow.showAtLocation(view, Gravity.TOP | Gravity.LEFT, x, y);
        }
    }

    private void initSharePopupWindow() {
        mShareWindow = new SharePopupWindow(this, 1);
        mShareWindow.setBg(dialogBgRl);
        mSharePopupWindow = mShareWindow.initPopWindow();
    }

    private void initLoginPopupWindow() {
        mLoginPopupWindow = new LoginPopupWindow(this, new LoginPopupWindow.LoginListener() {
            @Override
            public void onLoginListener(boolean isLoginSuccess) {
                if (isLoginSuccess) {
                    doDownLoad();
                }
            }
        });
        mLoginPopupWindow.setBg(dialogBgRl);
        mLoginPw = mLoginPopupWindow.initPopWindow();
    }

    private void initLoading() {
        loading = findViewById(R.id.video_loading);
        mLoadingIv = (ImageView) findViewById(R.id.loading_progressBar);
        animationDrawable = (AnimationDrawable) mLoadingIv.getDrawable();
        animationDrawable.start();
        loading_failed = findViewById(R.id.video_loading_failed);
        loading_failed.setVisibility(View.GONE);
    }

    /**
     * 云盘上报
     */
    private void CloudDetailReport() {
        String name = videoTitle;
        UmengEventPoster.postCloudDetail(name);
    }

    /**
     * 云盘下载上报
     */
    private void CloudDownloadReport() {
        String name = videoTitle;
        UmengEventPoster.postCloudDownload(name);
    }

    private void setLoadingFailed() {
        loading.setVisibility(View.GONE);
        animationDrawable = (AnimationDrawable) mLoadingIv.getDrawable();
        animationDrawable.stop();
        scrollView.setVisibility(View.GONE);
        loading_failed.setVisibility(View.VISIBLE);
        btnRefresh = (Button) loading_failed.findViewById(R.id.bn_refresh);
        btnRefresh.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (requestTask != null) {
                    requestTask.cancel();
                }
                requestTask = new RequestVideoDataTask(MoviesApplication.getInstance(), mStartFrom);
                requestTask.start();

                LogUtils.e(TAG, "on reResume request addata !!!!prepare!!!!");
                requestAdData();// 请求广告数据

                setOnLoading();
            }
        });
    }

    private void setFullScreenOffline() {
        loading.setVisibility(View.GONE);
        animationDrawable = (AnimationDrawable) mLoadingIv.getDrawable();
        animationDrawable.stop();
        scrollView.setVisibility(View.GONE);
        mVideoPlayerLayout.setVisibility(View.GONE);
        noMovieLayout.setVisibility(View.VISIBLE);
    }

    private void setOnLoading() {
        loading.setVisibility(View.VISIBLE);
        animationDrawable = (AnimationDrawable) mLoadingIv.getDrawable();
        animationDrawable.start();
        scrollView.setVisibility(View.GONE);
        loading_failed.setVisibility(View.GONE);
    }

    private void setLoadingComplete() {
        loading.setVisibility(View.GONE);
        animationDrawable = (AnimationDrawable) mLoadingIv.getDrawable();
        animationDrawable.stop();
        scrollView.setVisibility(View.VISIBLE);
        loading_failed.setVisibility(View.GONE);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            if (video != null && mPlayData != null) {
                if (Constants.TAG_IQIYI_SDK.equals(video.getSubsrc()) && Constants.SDK_IQIYI.equals(mPlayData.getPlayer())) {
                    if (mVideoPlayerLayout != null && mVideoPlayerLayout.getHeight() > mVideoPlayerLayout.getWidth()) {
                        setOrientation(false);
                        setFullScreen(false, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    }
                }
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.action_icon_layout:
                onOptionsItemSelected((MenuItem) (v.getTag()));
                break;
            case R.id.rl_episode_intro:
                setClickable(false);
                mRelativeLayout.setVisibility(View.VISIBLE);
                mRelativeLayout.setAnimation(AnimationUtils.loadAnimation(this, R.anim.dialog_push_in));
                if (getCurrentShowingEpisodePlayAdapter() != null) {
                    getCurrentShowingEpisodePlayAdapter().setmSelectProder(mCurrentPlayingPorder);
                    getCurrentShowingEpisodePlayAdapter().notifyDataSetChanged();
                }
                //修复剧集显示错误问题
                if (!TextUtils.isEmpty(showType)&&video!=null&&video.getEpisodeList().size()>0){
                    setEpisodesPopupData(video.getEpisodeList(),showType);
                }
                break;
            case R.id.iv_more_detail:
//                mIntroPopup.showAsDropDown(mActionView, 0, UIs.dipToPx(220));
//                showDialogBg(mIntroPopup);
                introduceview.setVisable(mMoreIcon);
                break;
            case R.id.rl_title:
//                mIntroPopup.showAsDropDown(mActionView, 0, UIs.dipToPx(220));
//                showDialogBg(mIntroPopup);
                introduceview.setVisable(mMoreIcon);
                break;
            case R.id.rl_score:
//                mIntroPopup.showAsDropDown(mActionView, 0, UIs.dipToPx(220));
//                showDialogBg(mIntroPopup);
                introduceview.setVisable(mMoreIcon);
                break;

            case R.id.ly_play_to_web:
                if (video.getEpisodeList() != null && mCurrentPlayPisiotion < video.getEpisodeList().size()) {
                    Episode episode = video.getEpisodeList().get(mCurrentPlayPisiotion);
                    PlayActivityFroWebView.openActivity(VideoDetailActivity.this, episode,
                            true, video.getAid(), video.getName(), video.getSitename(), mPlayData.getScript(),video.getSubsrc());
                    // 埋点
                    setStatistics(episode);
                    // 保存历史记录
                    saveToPlayRecord(episode, 0);
                }
                break;
        }
    }

    private void setStatistics(Episode episode) {
        mPlayStatusReport = new PlayStatusReporter();
        bigDataPlayReporter = new BigDataPlayReporter();
        // 服务器上报
        mPlayStatusReport.setAction(MoviesConstant.STATE_ACTION_PLAY);
        mPlayStatusReport.setSubsrc(Constants.TAG_IQIYI_SDK + Constants.TAG_SDK);
        mPlayStatusReport.setStartPlayTime(System.currentTimeMillis());
        mPlayStatusReport.setState(MoviesConstant.CLICK_IQIYI_PLAY_BTN);
        if (episode != null) {
            if (!TextUtils.isEmpty(episode.getCloudId())) {
                mPlayStatusReport.setmCloudId(episode.getCloudId());
            }
            if (!TextUtils.isEmpty(episode.getPorder())) {
                mPlayStatusReport.setPorder(episode.getPorder());
            }
            if (!TextUtils.isEmpty(episode.getPlay_url())) {
                mPlayStatusReport.setVid(episode.getPlay_url());
            }
            if (!TextUtils.isEmpty(episode.getVid())) {
                bigDataPlayReporter.setVid(episode.getVid());
            }
        }
        if (!TextUtils.isEmpty(video.getAid())) {
            mPlayStatusReport.setAid(video.getAid());
            bigDataPlayReporter.setPid(video.getAid()).setVid(video.getAid());
        } else {
            bigDataPlayReporter.setPid("-").setVid("-");
        }
        new ReportPlayStatusTask(MoviesApplication.getInstance(), mPlayStatusReport).start();
        // 大数据上报
        bigDataPlayReporter.setNt(BigDataUtils.getNetType(this));
        bigDataPlayReporter.setPlayType(BigDataConstants.TY_ONLINE);
        bigDataPlayReporter.setSource(Constants.TAG_IQIYI_SDK);
        bigDataPlayReporter.setPy(bigDataPlayReporter.getPy() + "&player=sdk");
        bigDataPlayReporter.setAc(BigDataConstants.PLAY_AC_INIT);
        bigDataPlayReporter.onPlayProcess();

    }

    /**
     * 保存播放记录
     */
    private void saveToPlayRecord(Episode ep, long currentPosition) {
        if (ep != null && mPlayData != null && null != mPlayData.getmPlayRecord()) {
            mPlayData.getmPlayRecord().setPageIndex(ep.getPageIndex());
            mPlayData.getmPlayRecord().setCurrentPagePosition(ep.getCurrentPagePosition());
            mPlayData.getmPlayRecord().setName(mPlayData.getmViewName());
            mPlayData.getmPlayRecord().setPorder(ep.getPorder());
            mPlayData.getmPlayRecord().setUrl(ep.getPlay_url());
            mPlayData.getmPlayRecord().setEpisodeName(ep.getPorder());
            mPlayData.getmPlayRecord().setSeekHistory(currentPosition);
            mPlayData.getmPlayRecord().setVid(ep.getGlobaVid());
            mPlayData.getmPlayRecord().setTime(System.currentTimeMillis());
            mPlayData.getmPlayRecord().setPoster(mPlayData.getPoster());
            mPlayData.getmPlayRecord().setSite(TextUtils.isEmpty(ep.getSite()) ? mPlayData.getSite() : ep.getSite());
            if (mLoginSP != null && !TextUtils.isEmpty(mLoginSP.getString(LoginActivity.TOKEN, ""))) {
                List<PlayRecord> list = new ArrayList<PlayRecord>();
                list.add(mPlayData.getmPlayRecord());
                new RequestDoPlayRecordTask(MoviesApplication.getInstance(), list, "add").start();
            } else {
                mPlayRecordDao.save(mPlayData.getmPlayRecord());
            }
        }
    }

    private void initViewPager() {
        scrollView = (ScrollView) findViewById(R.id.video_detail_scrollview);
        scrollView.setVisibility(View.GONE);
    }

    @Override
    public void requestSuccess(int updateId, Object data, String name) {
        if (name.equals(MoviesHttpApi.ADD_FAVORITE)) {//添加收藏成功
            if ("".equals(mLoginSp.getString(LoginActivity.TOKEN, ""))) {
                favoriteDao.save(bean);
            }
        } else if (name.equals(MoviesHttpApi.REMOVE_FAVORITE)) {//取消收藏成功
            UIs.showToast(getString(R.string.cancel_favorite_txt));
            mFavoriteImage.setImageResource(R.drawable.collection_icon_selector);
            isFavorite = false;
        } else if (name.equals(MoviesHttpApi.IS_FAVORITE_SYNC)) {//是否已经收藏
            if ("0".equals(((IsFavoriteBean) data).getData())) {
                mFavoriteImage.setImageResource(R.drawable.collection_icon_solid);
                isFavorite = true;
            }
        } else {

        }
    }

    @Override
    public void requestFail(String name) {
        if (name.equals(MoviesHttpApi.ADD_FAVORITE)) {//添加收藏失败
            favoriteDao.save(bean);
        } else if (name.equals(MoviesHttpApi.REMOVE_FAVORITE)) {//取消收藏失败
            UIs.showToast("取消收藏失败");
        } else if (name.equals(MoviesHttpApi.IS_FAVORITE_SYNC)) {//是否已经收藏

        } else {

        }

    }

    @Override
    public void netError(String name) {
        ToastUtil.showShortToast(this, getResources().getString(R.string.net_error));
        if (name.equals(MoviesHttpApi.ADD_FAVORITE)) {//添加收藏失败
            favoriteDao.save(bean);
        } else if (name.equals(MoviesHttpApi.REMOVE_FAVORITE)) {//取消收藏失败

        } else if (name.equals(MoviesHttpApi.IS_FAVORITE_SYNC)) {//是否已经收藏

        } else {

        }

    }

    private void initView() {
        mRetryLinearLayout = (LinearLayout)findViewById(R.id.ll_retry);
        mPlayStatus = (LinearLayout)findViewById(R.id.ll_play_status);
        introduceview = (IntroduceView) findViewById(R.id.introduceview_lay);
        mRelativeLayout = (RelativeLayout) findViewById(R.id.vs_episode_page);
        mDownLoadRelativeLayout = (RelativeLayout) findViewById(R.id.vs_episode_download_page);
        mMoreIcon = (ImageView) findViewById(R.id.iv_more_icon);

        mPlayerControl = (RelativeLayout) findViewById(R.id.video_player_control);
        mPlayBackButton = (ImageView) findViewById(R.id.video_player_playback_btn);
        mPlayBackButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mIsHalfScreen || mPlayMediaController == null) {
                    MoviesApplication.getInstance().startMainFromPushBack(mCurActivity, null);
                    exitPlay();
                } else {
                    setOrientation(false);
                    setFullScreen(false, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            }
        });
        mPlayerStatusImage = (TextView) findViewById(R.id.iv_status);
        mPlayerStatus = (TextView) findViewById(R.id.tv_video_description);
        playSrcIconIv = (ImageView) findViewById(R.id.iv_play_src_icon);
        playSrcTips = (TextView) findViewById(R.id.tv_source_tips);
        playSrcTips.setOnClickListener(new PlaySrcOnClickListener());

        playSrcIconIv.setOnClickListener(new PlaySrcOnClickListener());
        mFavoriteImage = (ImageView) findViewById(R.id.iv_video_collection);
        mFavoriteImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                int netType = NetWorkTypeUtils.reportNetType(VideoDetailActivity.this);
                if (netType == NetWorkTypeUtils.TYPE_WIFI || netType == NetWorkTypeUtils.TYPE_MOBILE) {
                    favorite();
                } else {
                    ToastUtil.showShortToast(VideoDetailActivity.this, getResources().getString(R.string.neterror));
                }
            }
        });
        mDownloadImage = (ImageView) findViewById(iv_video_download);
        mShareImage = (ImageView) findViewById(R.id.iv_video_share);
        mShareImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                int netType = NetWorkTypeUtils.reportNetType(VideoDetailActivity.this);
                if (netType == NetWorkTypeUtils.NETTYPE_NO || netType == NetWorkTypeUtils.TYPE_ERROR) {
                    ToastUtil.showShortToast(VideoDetailActivity.this, getResources().getString(R.string.neterror));
                    return;
                }
                if (mCurrentPopup != null && mCurrentPopup.isShowing()) {
                    return;
                }
                if (null != mSharePopupWindow) {
                    mSharePopupWindow.showAsDropDown(mActionView, 0, UIs.dipToPx(350));
                    showDialogBg(mSharePopupWindow);

                    MyDataRecord record = MyDataRecordCreater.build(MyDataRecord.class);
                    record.setAcode(SelfDataConstant.AC_SHARE);
                    record.setAid(aid);
                    RealmDaoManager.addMyDataRecord(record);

                }
            }
        });
        mTitleView = (TextView) findViewById(R.id.tv_video_name);
        noMovieLayout = findViewById(R.id.video_no_movie_layout);
        mVideoPlayerLayout = (FrameLayout) findViewById(R.id.fl_video_player_layout);
        int height = (Utils.getWidthPixels(this) * Utils.getWidthPixels(this)) / Utils.getHeightPixels(this);
        mVideoPlayerLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, height));
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, Utils.getHeightPixels(this) - height - UIs.getStatusBarHeight());

        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        mRelativeLayout.setLayoutParams(params);
        mDownLoadRelativeLayout.setLayoutParams(params);
        mPlayPopLinearLayout = (LinearLayout) findViewById(R.id.ll_play_pop_window);
        mPlayPopLinearLayout.setVisibility(View.VISIBLE);
        mPopPlayImageView = (ImageView) findViewById(R.id.iv_play);
        mPopImageView = (ImageView) findViewById(R.id.iv_pop_icon);
        mPopImageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPopupWindow.isShowing()) {
                    mPopupWindow.dismiss();
                } else {
                    showPopWindow(mPlayPopLinearLayout);
                    mPopImageView.setClickable(false);
                }
            }
        });
        mWebPageImageView = (ImageView) findViewById(R.id.iv_webpage_play);

        mLoginSp = getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE);

        playDetailContentRl = (RelativeLayout) findViewById(R.id.play_detail_content_rl);
        mVideoBgIv = (ImageView) findViewById(R.id.video_bg_iv);
        playIv = (ImageView) findViewById(R.id.play_iv);
        downloadIv = (ImageView) findViewById(R.id.download_iv);
        offlineIv = (ImageView) findViewById(R.id.offline_iv);
        poster = (ImageView) findViewById(R.id.video_poster);

        mYearTxt = (TextView) findViewById(R.id.tv_year);
        mRating = (TextView) findViewById(R.id.tv_score);
        mCategoryTxt = (TextView) findViewById(R.id.tv_category);
        mAreaTxt = (TextView) findViewById(tv_area);
        lineAdTop = (RelativeLayout) findViewById(R.id.rl_divide_line) ;
        playSrcLl = (RelativeLayout) findViewById(R.id.tv_play_src_more);
        playSrcTxtTv = (TextView) findViewById(R.id.play_src_txt_tv);
        introduceMoreTv = (RelativeLayout) findViewById(R.id.iv_more_detail);
        introduceMoreTv.setOnClickListener(this);
        findViewById(R.id.rl_title).setOnClickListener(this);
        findViewById(rl_score).setOnClickListener(this);
        episodeDataLl = (LinearLayout) findViewById(R.id.episode_data_ll);
        episodeTitleTv = (TextView) findViewById(R.id.episode_title_tv);
        moreEpisodeTv = (TextView) findViewById(R.id.more_episode_tv);
        allEpisode = (RelativeLayout) findViewById(R.id.rl_episode_intro);
        allEpisode.setOnClickListener(this);
        episodeListview = (RecyclerView) findViewById(R.id.episode_listview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        episodeListview.setLayoutManager(linearLayoutManager);
//        varietyListview = (RecyclerView) findViewById(R.id.variety_listview);
        mlyBtnPlayWeb = (LinearLayout) findViewById(R.id.ly_play_to_web);
        mlyBtnPlayWeb.setOnClickListener(this);

        relativeRecommendLl = (LinearLayout) findViewById(R.id.relative_recommend_ll);
        lineRelativeTop = (RelativeLayout) findViewById(R.id.line_relative_top);
        relativeListview = (RecyclerView) findViewById(R.id.relative_listview);
        relativeListview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                relativeListview.clearFocus();
                relativeListview.setFocusable(false);
            }
        });
        LinearLayoutManager relationLinearLayoutManager = new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        relativeListview.setLayoutManager(relationLinearLayoutManager);
        mReportImageView = (RelativeLayout) findViewById(R.id.rl_detail_report_image);
        mReportImageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(VideoDetailActivity.this, ReportActivity.class);
                intent.putExtra("aid", aid);
                intent.putExtra("site", getmCrrentSite());
                startActivity(intent);
            }
        });
        if (!NEED_REPORT.equals(PreferencesManager.getInstance().getReport())) {
            mReportImageView.setVisibility(View.GONE);
        }

        dialogBgRl = (RelativeLayout) findViewById(R.id.dialog_bg_rl);
        dialogBgRl.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                UIs.showOrHideBg(dialogBgRl, false);
                if (mCurrentPopup != null && mCurrentPopup.isShowing()) {
                    mCurrentPopup.dismiss();
                }
            }
        });

        // 播放源popupwindow
        initIntroPopup();
        initPlaySrcPopup();
        initEpisodesPopup();

        initDownloadPopup();
        initDownLoadEpisodesPopup();
        mDownloadImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                int netType = NetWorkTypeUtils.reportNetType(VideoDetailActivity.this);
                if (netType == NetWorkTypeUtils.NETTYPE_NO || netType == NetWorkTypeUtils.TYPE_ERROR) {
                    ToastUtil.showShortToast(VideoDetailActivity.this, getResources().getString(R.string.neterror));
                    return;
                }

                if (mCurrentPopup != null && mCurrentPopup.isShowing()) {
                    return;
                }
                if (null != mLoginPw && TextUtils.isEmpty(mLoginSp.getString(LoginActivity.TOKEN, ""))) {
                    LoginDataRecord loginDataRecord = MyDataRecordCreater.build(LoginDataRecord.class);
                    loginDataRecord.setCur_url("halfscreen");
                    loginDataRecord.setAcode("0");
                    loginDataRecord.setAction("download_btn");
                    RealmDaoManager.addMyDataRecord(loginDataRecord);
                    UmengEventPoster.doEventPost(UmengEventPoster.CLICK_TO_LOGIN);
                    mLoginPw.showAtLocation(mActionView, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
                    showDialogBg(mLoginPw);

                    LoginDataRecord showLoginPoPRecord = MyDataRecordCreater.build(LoginDataRecord.class);
                    showLoginPoPRecord.setCur_url("layer_login");
                    showLoginPoPRecord.setRef_url("halfscreen");
                    showLoginPoPRecord.setAcode("41");
                    RealmDaoManager.addMyDataRecord(showLoginPoPRecord);
                } else {
                    LoginDataRecord loginDataRecord = MyDataRecordCreater.build(LoginDataRecord.class);
                    loginDataRecord.setCur_url("halfscreen");
                    loginDataRecord.setAcode("0");
                    loginDataRecord.setAction("download_btn");
                    RealmDaoManager.addMyDataRecord(loginDataRecord);
                    doDownLoad();
                }
            }
        });
        // 播放源点击事件
        playSrcLl.setOnClickListener(new PlaySrcOnClickListener());
        playSrcLl.setEnabled(false);

        favoriteDao = new FavoriteDao(this);

        mProgressDialog = new Dialog(this, R.style.PlaySrcLoadingDialog);
        mProgressDialog.setContentView(R.layout.loading_dialog);
        mProgressDialog.setCancelable(false);
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case LANDSCAPE:
                        if (mIsHalfScreen) {
                            setFullScreen(true, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        }
                        mClickInPort = false;
                        break;
                    case LANDSCAPE_REVERSE:
                        if (mIsHalfScreen) {
                            setFullScreen(true, ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
                        }
                        mClickInPort = false;
                        break;
                    case PORTRAIT:
                        if (!mIsHalfScreen) {
                            setFullScreen(false, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                        }
                        mClickInLand = false;
                        break;
                    case PLAY_CONTROL_ON_RESUME:
                        if (!Utils.getScreenLockStatus() && null != mPlayMediaController) {
                            if (!updatePlayPageInWorkMobile()) {
                                if (getResources().getText(R.string.play_in_mobile_des).equals(mPlayerStatusImage.getText())) {
                                    mPlayerStatusImage.setVisibility(View.GONE);
                                    mPlayerStatus.setVisibility(View.GONE);
                                }
                                mPlayMediaController.onResume();
                            }
                        }
                        break;

                }
                super.handleMessage(msg);
            }
        };
        mOrientationListener = new OrientationEventListener(this) {
            @Override
            public void onOrientationChanged(int rotation) {
                // 设置横屏
                if (Settings.System.getInt(getContentResolver(),
                        Settings.System.ACCELEROMETER_ROTATION, 0) == SCREEN_ROTATION_ON &&
                        findViewById(R.id.videoplayer_lockscreen) != null &&
                        !(findViewById(R.id.videoplayer_lockscreen)).isSelected()) {
                    LogUtils.e("or", "orientation is " + rotation);
                    if ((rotation >= FULL_SCREEN_LAND_MIN_DEGREE) && (rotation <= FULL_SCREEN_LANDSCAPE_MAX_DEGREE)) {
                        if (!mClickInLand) {
                            mHandler.removeMessages(LANDSCAPE);
                            mHandler.removeMessages(PORTRAIT);
                            mHandler.sendEmptyMessageDelayed(LANDSCAPE_REVERSE, 800);
                        }
                    } else if ((rotation > FULL_SCREEN_LANDSCAPE_MAX_DEGREE) && (rotation < FULL_SCREEN_REVERSE_MIN_DEGREE)) {
                        if (!mClickInLand) {
                            mHandler.removeMessages(LANDSCAPE_REVERSE);
                            mHandler.removeMessages(PORTRAIT);
                            mHandler.sendEmptyMessageDelayed(LANDSCAPE, 800);
                        }
                    } else if ((rotation <= 360 && rotation > FULL_SCREEN_REVERSE_MIN_DEGREE) ||
                            (rotation < FULL_SCREEN_LAND_MIN_DEGREE && rotation >= 0)) {
                        if (!mClickInPort) {
                            mHandler.removeMessages(LANDSCAPE_REVERSE);
                            mHandler.removeMessages(LANDSCAPE);
                            mHandler.sendEmptyMessageDelayed(PORTRAIT, 500);
                        }
                    }
                }
            }
        };
        mOrientationListener.enable();

    }

    public void resumePlay() {
        if (mPlayMediaController == null) {
            mPlayMediaController = new PlayMediaController(VideoDetailActivity.this, mVideoPlayerLayout);
            mPlayMediaController.setmNetClarityListener(VideoDetailActivity.this);
        }
        mPlayerStatusImage.setVisibility(View.GONE);
        mPlayerStatus.setVisibility(View.GONE);
        if ((NetWorkTypeUtils.getNetType() == NetWorkTypeUtils.NETTYPE_3G || NetWorkTypeUtils.getNetType()
                == NetWorkTypeUtils.NETTYPE_2G || NetWorkTypeUtils.getNetType()
                == NetWorkTypeUtils.NETTYPE_4G)) {
            MoviesConstant.isFirstIn4GPlayVideo = false;
            MoviesConstant.isIn4GPlayVideo = true;
        }
        if (getPlayingProcess()) {
            mPlayMediaController.onResume();
        } else {
            if(video == null) {
                return;
            }
            PlayVideoInSmallScreen(findEpisodeByPorder(mCurrentPlayingPorder, video.getEpisodeList()));
        }
    }

    public void exitPlay() {
        if (null != mPlayMediaController) {
            LinearLayout selectLayout = mPlayMediaController.getmSelectLinearLayout();
            if (null != selectLayout && selectLayout.isShown()) {
                mPlayMediaController.selectUiChange();
            } else {
                mPlayMediaController.playerPause();
                mPlayMediaController.onUserFinish();
                mPlayMediaController.resetPlayData();
                mPlayMediaController.releaseData();
            }
            reportUMengPlayer();
            mPlayMediaController.stopTimeCircleReport();
            mPlayMediaController.unitPptv();
        }
        finish();
    }

    /**
     * 进行播放劫流上报
     * zhangshuo
     * 2014年5月5日 下午5:44:15
     */
    private void reportUMengPlayer() {
        UMengReport uMengReport = mPlayMediaController.getmUMengReport();
        if (!uMengReport.ismIsReported()) {
            uMengReport.setEndLoadingTime(System.currentTimeMillis());
            String playResult = uMengReport.getIsMoreThan30() ? UmengEventPoster.PLAYER_RESULT_30_MORE_CANCEL
                    : UmengEventPoster.PLAYER_RESULT_30_CANCEL;
            uMengReport.setPlayresult(playResult);
            uMengReport.setmIsReported(true);
            UmengEventPoster.postPlayer(uMengReport);
        }
    }

    /**
     * 下载 浮层 初始化
     */
    private void initDownLoadEpisodesPopup() {
        mDownLoadTabs = (SlidingTabLayout) mDownLoadRelativeLayout.findViewById(R.id.episode_download_page_tabs);
        mDownLoadViewPager = (ViewPager) mDownLoadRelativeLayout.findViewById(R.id.episode_download_pager);
        ((TextView) mDownLoadRelativeLayout.findViewById(R.id.title_tv)).setText(R.string.menu_download);
        RelativeLayout cancelIv = (RelativeLayout) mDownLoadRelativeLayout.findViewById(R.id.right_close_iv);
        cancelIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mDownLoadRelativeLayout.setAnimation(AnimationUtils.loadAnimation(VideoDetailActivity.this, R.anim.dialog_push_out));
                mDownLoadRelativeLayout.setVisibility(View.GONE);
                setClickable(true);
                UIs.showOrHideBg(dialogBgRl, false);
            }
        });

        TextView rightTv = (TextView) mDownLoadRelativeLayout.findViewById(R.id.right_tv);
        rightTv.setText(R.string.download_manager_list);
        rightTv.setVisibility(View.VISIBLE);
        mDownLoadRelativeLayout.findViewById(R.id.iv_download_list_lay).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(VideoDetailActivity.this,
                        DownloadActivity.class);
                startActivity(intent);
            }
        });
        downloadedNumTv = (TextView) mDownLoadRelativeLayout.findViewById(R.id.download_num_tv);
//        mDownloadHeader = (LinearLayout) mDownLoadRelativeLayout.findViewById(R.id.ll_popup_download);

        mDefinition_fluency = (TextView) mDownLoadRelativeLayout.findViewById(R.id.definition_fluency_tv);
        mDefinition_common = (TextView) mDownLoadRelativeLayout.findViewById(R.id.definition_common_tv);
        mDefinition_highclear = (TextView) mDownLoadRelativeLayout.findViewById(R.id.definition_highclear_tv);
        mDefinition_super = (TextView) mDownLoadRelativeLayout.findViewById(R.id.definition_super_tv);

        mDefinition_fluency.setOnClickListener(clarityClickListener);
        mDefinition_common.setOnClickListener(clarityClickListener);
        mDefinition_highclear.setOnClickListener(clarityClickListener);
        mDefinition_super.setOnClickListener(clarityClickListener);

    }

    private void initDownloadPopup() {
        initDownloadMoveView();
        mDownloadPopup = new PopupWindow(downloadPopupMoveView, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        mDownloadPopup.setAnimationStyle(R.style.sharepopupAnimation);

        if (null != mDownloadPopup) {
            mDownloadPopup.setFocusable(false);
            mDownloadPopup.setBackgroundDrawable(new BitmapDrawable());
            mDownloadPopup.setOutsideTouchable(false);
            mDownloadPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        }
    }

    private void initIntroPopup() {
        View introPopupView = View.inflate(this, R.layout.popup_introduce_layout, null);
        mIntroPopup = new PopupWindow(introPopupView, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        mIntroPopup.setAnimationStyle(R.style.sharepopupAnimation);
        year = (TextView) introPopupView.findViewById(R.id.play_year);
        director = (TextView) introPopupView.findViewById(R.id.play_director);
        starring = (TextView) introPopupView.findViewById(R.id.play_starring);
        score = (TextView) introPopupView.findViewById(R.id.tv_intro_score);
        if (null != mIntroPopup) {
            mIntroPopup.setFocusable(false);
            mIntroPopup.setBackgroundDrawable(new BitmapDrawable());
            mIntroPopup.setOutsideTouchable(false);
            mIntroPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        }
        TextView introTitleTv = (TextView) introPopupView.findViewById(R.id.title_tv);
        introPopupTv = (TextView) introPopupView.findViewById(R.id.intro_tv);
        introTitleTv.setText(videoTitle);
        TextPaint tp = introTitleTv.getPaint();
        tp.setFakeBoldText(true);
        RelativeLayout cancelIv = (RelativeLayout) introPopupView.findViewById(R.id.right_close_iv);
        cancelIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mIntroPopup.dismiss();
                UIs.showOrHideBg(dialogBgRl, false);
            }
        });
    }

    private void initEpisodesPopup() {
        mTabs = (SlidingTabLayout) mRelativeLayout.findViewById(R.id.episode_page_tabs);
        mViewPager = (ViewPager) mRelativeLayout.findViewById(R.id.episode_pager);
        RelativeLayout cancelIv = (RelativeLayout) mRelativeLayout.findViewById(R.id.right_close_iv);
        cancelIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                hideEpisodeFragment();
                UIs.showOrHideBg(dialogBgRl, false);
            }
        });
    }

    public void hideEpisodeFragment() {
        mRelativeLayout.setAnimation(AnimationUtils.loadAnimation(VideoDetailActivity.this, R.anim.dialog_push_out));
        mRelativeLayout.setVisibility(View.GONE);
        setClickable(true);
    }

    private void initPlaySrcPopup() {
        View playSrcPopupView = View.inflate(this, R.layout.popup_src_layout, null);
        mPlaySrcPopup = new PopupWindow(playSrcPopupView, LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        if (null != mPlaySrcPopup) {
            ;
            mPlaySrcPopup.setBackgroundDrawable(new BitmapDrawable());
            mPlaySrcPopup.setOutsideTouchable(true);
            mPlaySrcPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        }
        mSrcListview = (ListView) playSrcPopupView.findViewById(R.id.src_listview);
    }

    /**
     * 清晰度切换监听事件
     */
    private OnClickListener clarityClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if ("letv".equalsIgnoreCase(video.getSubsrc()) && 0 == MoviesConstant.letvPlayStatus) {
                switch (v.getId()) {
                    case R.id.definition_super_tv:
                        mdefaultClarity = DefinitionManager.DEFINITION_TYPE_SUPER;
                        break;
                    case R.id.definition_highclear_tv:
                        mdefaultClarity = DefinitionManager.DEFINITION_TYPE_HIGH;
                        break;
                    case R.id.definition_common_tv:
                        mdefaultClarity = DefinitionManager.DEFINITION_TYPE_NORMAL;
                        break;
                    case R.id.definition_fluency_tv:
                        mdefaultClarity = DefinitionManager.DEFINITION_TYPE_FLUENCY;
                        break;
                }
                if (video.getVt().equals(MoviesConstant.VT_MOVIE)) {

                    Episode ep = video.getEpisodeList().get(0);
                    if (downLoadManager.selectDownloadJobByMid(ep.getSerialid())) {
                        ToastUtil.showShortToast(
                                MoviesApplication.getInstance(),
                                R.string.down_exists);
                    } else {
                        if (NetWorkTypeUtils.reportNetType(VideoDetailActivity.this) == 2
                                && !IsDownloadcan3g()) {
                            checkIfContinueDownloadDialog(0, null, video.getAid(), ep,
                                    video.getSubsrc(), addTime);
                        } else {
                            updateAddedDownloadItem(0, null, video.getAid(), ep,
                                    video.getSubsrc(), addTime);
                            bdDownloadDataMap = BigDataApi.createDataMap("2", "", "0", video.getCategory(), video.getAid(), ep.getGlobaVid());
                            confirmDownload(0);
                        }
                        initClarityUI(false);
                    }
                    // 判断是否允许3g下载
                } else {
//                    if(mDownLoadCurrentEpisodePlayAdapter != null){
//                        mDownLoadCurrentEpisodePlayAdapter.setPls(mdefaultClarity);
//                    }
                    initClarityUI(false);
                }
            } else if (PlayerUtils.isOutSite(video.getSubsrc()) || ("letv".equalsIgnoreCase(video.getSubsrc()) && 0 != MoviesConstant.letvPlayStatus)) {
                switch (v.getId()) {
                    case R.id.definition_super_tv:
                        mOutsiteClarity = MoviesConstant.SUPER2;
                        break;
                    case R.id.definition_highclear_tv:
                        mOutsiteClarity = MoviesConstant.SUPER;
                        break;
                    case R.id.definition_common_tv:
                        mOutsiteClarity = MoviesConstant.HIGH;
                        break;
                    case R.id.definition_fluency_tv:
                        mOutsiteClarity = MoviesConstant.NORMAL;
                        break;
                }
                if (video.getVt().equals(MoviesConstant.VT_MOVIE)) {
                    Episode ep = video.getEpisodeList().get(0);
                    if (downLoadManager.selectDownloadJobByMid(ep.getSerialid())) {
                        ToastUtil.showShortToast(
                                MoviesApplication.getInstance(),
                                R.string.down_exists);
                    } else {
                        // 判断是否允许3g下载
                        if (NetWorkTypeUtils.reportNetType(VideoDetailActivity.this) == 2
                                && !IsDownloadcan3g()) {
                            checkIfContinueDownloadDialog(0, null, video.getAid(), ep,
                                    video.getSubsrc(), addTime);
                        } else {
                            updateAddedDownloadItem(0, null, video.getAid(), ep,
                                    video.getSubsrc(), addTime);
                            bdDownloadDataMap = BigDataApi.createDataMap("2", "", "0", video.getCategory(), video.getAid(), ep.getGlobaVid());
                            confirmDownload(0);
                        }
                        initOutSiteClarityUI();
                    }
                } else {
                    initOutSiteClarityUI();
                }
            } else if ("nets".equalsIgnoreCase(video.getSubsrc())) {
                switch (v.getId()) {
                    case R.id.definition_super_tv:
                        mdefaultClarity = DefinitionManager.DEFINITION_TYPE_SUPER;
                        break;
                    case R.id.definition_highclear_tv:
                        mdefaultClarity = DefinitionManager.DEFINITION_TYPE_HIGH;
                        break;
                    case R.id.definition_common_tv:
                        mdefaultClarity = DefinitionManager.DEFINITION_TYPE_NORMAL;
                        break;
                    case R.id.definition_fluency_tv:
                        mdefaultClarity = DefinitionManager.DEFINITION_TYPE_FLUENCY;
                        break;
                }
                if (video.getVt().equals(MoviesConstant.VT_MOVIE)) {
                    Episode ep = video.getEpisodeList().get(0);
                    if (downLoadManager.selectDownloadJobByMid(ep.getSerialid())) {
                        ToastUtil.showShortToast(
                                MoviesApplication.getInstance(),
                                R.string.down_exists);
                    } else {
                        // 判断是否允许3g下载
                        if (NetWorkTypeUtils.reportNetType(VideoDetailActivity.this) == 2
                                && !IsDownloadcan3g()) {
                            checkIfContinueDownloadDialog(0, null, video.getAid(), ep,
                                    video.getSubsrc(), addTime);
                        } else {
                            updateAddedDownloadItem(0, null, video.getAid(), ep,
                                    video.getSubsrc(), addTime);
                            bdDownloadDataMap = BigDataApi.createDataMap("2", "", "0", video.getCategory(), video.getAid(), ep.getGlobaVid());
                            confirmDownload(0);
                        }
                        initClarityNetUI();
                    }
                } else {
                    initClarityNetUI();
                }
            }
        }
    };

    /**
     *
     * 清晰度选择 高亮 UI
     */
    private void initOutSiteClarityUI() {
        mDefinition_super.setVisibility(View.VISIBLE);
        if (MoviesConstant.VT_MOVIE.equals(video.getVt())) {
            initMovieClarityUI();
            if (MoviesConstant.NORMAL.equalsIgnoreCase(mOutsiteClarity)) {
                mDefinition_fluency.setTextColor(getResources().getColor(R.color.color_3599f8));
                mMoveDefinition_fluency.setTextColor(getResources().getColor(R.color.color_3599f8));
            } else if (MoviesConstant.HIGH.equalsIgnoreCase(mOutsiteClarity)) {
                mDefinition_common.setTextColor(getResources().getColor(R.color.color_3599f8));
                mMoveDefinition_common.setTextColor(getResources().getColor(R.color.color_3599f8));
            } else if (MoviesConstant.SUPER.equalsIgnoreCase(mOutsiteClarity)) {
                mDefinition_highclear.setTextColor(getResources().getColor(R.color.color_3599f8));
                mMoveDefinition_highclear.setTextColor(getResources().getColor(R.color.color_3599f8));
            } else if (MoviesConstant.SUPER2.equalsIgnoreCase(mOutsiteClarity)) {
                mDefinition_super.setTextColor(getResources().getColor(R.color.color_3599f8));
                mMoveDefinition_super.setTextColor(getResources().getColor(R.color.color_3599f8));
            }
        } else {
            mDefinition_fluency.setBackgroundResource(R.color.white);
            mDefinition_fluency.setTextColor(getResources().getColor(R.color.color_ff333333));
            mDefinition_common.setBackgroundResource(R.color.white);
            mDefinition_common.setTextColor(getResources().getColor(R.color.color_ff333333));
            mDefinition_highclear.setBackgroundResource(R.color.white);
            mDefinition_highclear.setTextColor(getResources().getColor(R.color.color_ff333333));
            mDefinition_super.setBackgroundResource(R.color.white);
            mDefinition_super.setTextColor(getResources().getColor(R.color.color_ff333333));
            mMoveDefinition_fluency.setBackgroundResource(R.color.white);
            mMoveDefinition_fluency.setTextColor(getResources().getColor(R.color.color_ff333333));
            mMoveDefinition_common.setBackgroundResource(R.color.white);
            mMoveDefinition_common.setTextColor(getResources().getColor(R.color.color_ff333333));
            mMoveDefinition_highclear.setBackgroundResource(R.color.white);
            mMoveDefinition_highclear.setTextColor(getResources().getColor(R.color.color_ff333333));
            mMoveDefinition_super.setBackgroundResource(R.color.white);
            mMoveDefinition_super.setTextColor(getResources().getColor(R.color.color_ff333333));
            if (MoviesConstant.NORMAL.equalsIgnoreCase(mOutsiteClarity)) {
                mDefinition_fluency.setTextColor(getResources().getColor(R.color.color_3599f8));
                mMoveDefinition_fluency.setTextColor(getResources().getColor(R.color.color_3599f8));
            } else if (MoviesConstant.HIGH.equalsIgnoreCase(mOutsiteClarity)) {
                mDefinition_common.setTextColor(getResources().getColor(R.color.color_3599f8));
                mMoveDefinition_common.setTextColor(getResources().getColor(R.color.color_3599f8));
            } else if (MoviesConstant.SUPER.equalsIgnoreCase(mOutsiteClarity)) {
                mDefinition_highclear.setTextColor(getResources().getColor(R.color.color_3599f8));
                mMoveDefinition_highclear.setTextColor(getResources().getColor(R.color.color_3599f8));
            } else if (MoviesConstant.SUPER2.equalsIgnoreCase(mOutsiteClarity)) {
                mDefinition_super.setTextColor(getResources().getColor(R.color.color_3599f8));
                mMoveDefinition_super.setTextColor(getResources().getColor(R.color.color_3599f8));
            }
        }
    }

    /**
     * 控制清晰度UI
     */
    private void initClarityUI(boolean isFirstInit) {
        if (video.getEpisodeList() == null || video.getEpisodeList().size() < 1) {
            return;
        }
        Episode ep = null;
        if (video.getEpisodeList().size() > 0) {
            ep = video.getEpisodeList().get(0);
        }

//        mDownloadHeader.setVisibility(View.GONE);
//        mDefinition_super.setVisibility(View.GONE);
        if (MoviesConstant.VT_MOVIE.equals(video.getVt())) {
            initMovieClarityUI();
        }
        if (null != ep && !TextUtils.isEmpty(ep.getPls())) {
            String[] types = ep.getPls().split(",");
            List<String> typeList = Arrays.asList(types);
            HashMap<String, Boolean> mClaritymap = DefinitionManager.getSupportDefFlag(typeList);
//            defaultClarity(typeList);
            if (null != typeList) {
                if (MoviesConstant.VT_MOVIE.equals(video.getVt())) {
                    setClarityText(mMoveDefinition_super, DefinitionManager.DEFINITION_TYPE_SUPER.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_SUPER));
                    setClarityText(mMoveDefinition_highclear, DefinitionManager.DEFINITION_TYPE_HIGH.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_HIGH));
                    setClarityText(mMoveDefinition_common, DefinitionManager.DEFINITION_TYPE_NORMAL.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_NORMAL));
                    setClarityText(mMoveDefinition_fluency, DefinitionManager.DEFINITION_TYPE_FLUENCY.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_FLUENCY));
                } else {
                    setClarityText(mDefinition_super, DefinitionManager.DEFINITION_TYPE_SUPER.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_SUPER));
                    setClarityText(mDefinition_highclear, DefinitionManager.DEFINITION_TYPE_HIGH.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_HIGH));
                    setClarityText(mDefinition_common, DefinitionManager.DEFINITION_TYPE_NORMAL.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_NORMAL));
                    setClarityText(mDefinition_fluency, DefinitionManager.DEFINITION_TYPE_FLUENCY.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_FLUENCY));
                }

            }
        }
    }


    // 获取是否允许3g下载的数据
    public boolean IsDownloadcan3g() {
        SharedPreferences bgDownloadSharePreference = getSharedPreferences(
                SettingManage.SETTING_RELATIVE_SHAREPREFERENCE,
                Context.MODE_PRIVATE);
        Boolean IsDownloadcan3g = bgDownloadSharePreference.getBoolean(
                SettingManage.IS_DOWNLOAD_CAN_3G, false);
        return IsDownloadcan3g;
    }

    // 打开3g下载开关对话框
    private void checkIfContinueDownloadDialog(final int position,
                                               final SparseArray<Boolean> selectedList, final String mid,
                                               final Episode episode, final String site, final int addTime) {
        Builder customBuilder = new Builder(this);
        customBuilder
                .setTitle(R.string.tip)
                .setMessage(R.string.wireless_tip)
                .setPositiveButton(R.string.continue_download,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                mSettingManage.setToggleButtonPreference(true,
                                        mSettingPreferenceEditor,
                                        SettingManage.IS_DOWNLOAD_CAN_3G);
                                updateAddedDownloadItem(position, selectedList,
                                        mid, episode, site, addTime);
                                bdDownloadDataMap = BigDataApi.createDataMap("2", "", "0", video.getCategory(), video.getAid(), episode.getGlobaVid());
                                confirmDownload(position);
                                dialog.dismiss();
                            }
                        })
                .setNegativeButton(R.string.pause_download,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                            }
                        }).setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode,
                                 KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getRepeatCount() == 0) {
                    dialog.dismiss();
                }
                return false;
            }
        });
        Dialog dialog = customBuilder.create();
        dialog.show();
    }

    // 确认下载
    public void confirmDownload(int position) {
        boolean addDownloadSuccess = false;

        addDownloadSuccess = addToDownload();
        if (!addDownloadSuccess) {
            ToastUtil.showLongToast(MoviesApplication.getInstance(),
                    R.string.addfailure, position + 1);
            return;
        }
        new Handler().postDelayed(new Runnable() {

            public void run() {
                updateDownloadedEpisodesNum(downLoadManager);
            }

        }, 1000);

        ToastUtil.showLongToast(this, R.string.addok);

        BigDataApi.bigDataCommonReport(bdDownloadDataMap, VideoDetailActivity.this);
    }

    public boolean addToDownload() {
        boolean addSuccess = false;
        ArrayList<DownloadEntity> downloadList = MoviesApplication
                .getInstance().getDownloadManager().entitys;
        if (null != downloadList && downloadList.size() > 0) {
            MoviesApplication.getInstance().getDownloadManager().entitys = downloadList;
            MoviesApplication.getInstance().getDownloadManager().download();
            addSuccess = true;
        }
        return addSuccess;
    }

    public boolean updateAddedDownloadItem(int position,
                                           SparseArray<Boolean> selectedList, String mid, Episode episode,
                                           String site, int addTime) {
        boolean addSuccess = false;
        DownloadEntity entity = buildDownloadEntity(position, mid, episode,
                site, addTime);
        if (null != entity) {
            MoviesApplication.getInstance().getDownloadManager().add(entity);
        } else {
            LogUtils.i(TAG, "添加失败 -- position == " + position);
        }
        return addSuccess;
    }

    private DownloadEntity buildDownloadEntity(int position, String mediaid,
                                               Episode episode, String site, int addTime) {
        DownloadEntity entity = null;
        if (!TextUtils.isEmpty(mediaid) && null != episode) {
            String mediaName = PlayerUtils.getVideoName(video.getVt(), videoTitle, episode);
            entity = new DownloadEntity();
            entity.setPorder(episode.getPorder());
            entity.setMid(mediaid);
            entity.setMedianame(mediaName);
            entity.setSite(site);
            entity.setLVideoMid(episode.getMid());
            entity.setRequest_site(episode.getRequest_site());
            entity.setAddTime(addTime);
            entity.setFolderName(videoTitle);
            entity.setVt(video.getVt());
            entity.setPath(DownloadHelper.getDownloadPath());
            entity.setSnifferUrl(episode.getPlay_url());
            entity.setExternal_id(episode.getExternalId());
            entity.setGlobaVid(episode.getGlobaVid());
            entity.setSrc(video.getSrc());
            entity.setCategory(video.getCategory());
            entity.setMp4Slice("0");
            entity.setCurrClarity(DefinitionManager.PLS_MP4_800);
            if ("letv".equals(video.getSubsrc()) && 0 == MoviesConstant.letvPlayStatus) {
                String pls = episode.getPls();
                if (!TextUtils.isEmpty(pls) && pls.contains(",")) {
                    List<String> list = Arrays.asList(pls.split(","));
                    entity.setCurrClarity(DefinitionManager.getVideoCaseByDefType(list, mdefaultClarity, "-1"));
                }
            }
            if (PlayerUtils.isOutSite(video.getSubsrc()) || ("letv".equals(video.getSubsrc()) && 0 != MoviesConstant.letvPlayStatus)) {
                entity.setOutsiteClarity(mOutsiteClarity);
            }
            if ("nets".equals(video.getSubsrc())) {//云盘下载id
                entity.setCloudId(episode.getCloudId());
                String pls = episode.getPls();
                if (!TextUtils.isEmpty(pls) && pls.contains(",")) {
                    List<String> list = Arrays.asList(pls.split(","));
                    entity.setCurrClarity(DefinitionManager.getVideoCaseByDefType(list, mdefaultClarity, "-1"));
                }
            }
            if (null != episode) {
                entity.setId(episode.getSerialid());
                entity.setTaskname(episode.getPorder());
                String temp = episode.getPorder().replace("-", "").replace("_", "");
                if (temp.length() > 10) {
                    temp = temp.substring(temp.length() - 9);
                }
                if (temp.contains(".")) {
                    temp = Math.ceil(Double.parseDouble(temp)) + "";
                    temp.replace(".0", "");
                }
                int index;
                try {
                    index = Integer.parseInt(temp);
                } catch (Exception e) {
                    index = 0;
                    e.printStackTrace();
                }
                entity.setIndex(index);
                LogUtils.e("downLocal", "VideoDetailActivity setindex");
            }
            entity.setImgUrl(video.getPoster());
        }
        return entity;
    }

    private Favorite bean;

    private void favorite() {
        if (isFavorite == false && video != null) {
            bean = new Favorite();
            bean.setAid(aid);
            bean.setName(videoTitle);
            bean.setSrc(video.getSrc());
            bean.setPoster(video.getPoster());
            if (TextUtils.equals(video.getVt(), MoviesConstant.VT_MOVIE)) {
                bean.setDesc(String.format("主演：%s", video.getStarringname()));
            } else if (TextUtils
                    .equals(video.getVt(), MoviesConstant.VT_ZONGYI)) {
                if (video.getEpisodeList().size() > 0) {
                    bean.setDesc(video.getEpisodeList().get(0).getReleaseDate());
                } else {
                    bean.setDesc("");
                }
            } else {
                if (TextUtils.equals("1", video.getIsend())) {
                    bean.setDesc(String.format("%s集全", video.getEpisodes()));
                } else if (TextUtils.equals("0", video.getIsend())) {
                    bean.setDesc(String.format("更新至%s集", video.getNowepisodes()));
                } else {
                    bean.setDesc("");
                }
            }
            bean.setVt(video.getVt());
            bean.setNowEpisode(video.getNowepisodes());
            bean.setIsend(video.getIsend());
            UIs.showToast(getString(R.string.favorite_success_txt));
            isFavorite = true;
            mFavoriteImage.setImageResource(R.drawable.collection_icon_solid);
            if (!"".equals(mLoginSp.getString(LoginActivity.TOKEN, ""))) {
                mRequestAddFavoriteTask = new RequestAddFavoriteTask(MoviesApplication.getInstance(), aid, "1", video.getSitename());
                mRequestAddFavoriteTask.setRequestListener(this);
                mRequestAddFavoriteTask.start();
            } else {
                favoriteDao.save(bean);
            }
            Map<String, String> favoriteDataMap = BigDataApi.createDataMap("3", "", "0", video.getCategory(), video.getAid(), "-");
            BigDataApi.bigDataCommonReport(favoriteDataMap, VideoDetailActivity.this);
            RealDataApi.RealDataCollectionReport(video.getVid(), video.getAid(), video.getCategory(), seid, bucket);
            MyDataRecord record = MyDataRecordCreater.build(MyDataRecord.class);
            record.setAid(video.getAid());
            record.setAcode(SelfDataConstant.AC_FAVORITE);
            RealmDaoManager.addMyDataRecord(record);
        } else if (video != null) {
            if (favoriteDao.getByAid(aid) != null) {
                favoriteDao.delete(aid);
                UIs.showToast(getString(R.string.cancel_favorite_txt));
                mFavoriteImage.setImageResource(R.drawable.collection_icon_selector);
                isFavorite = false;
            } else {
                if (!"".equals(mLoginSp.getString(LoginActivity.TOKEN, ""))) {
                    mRequestRemoveFavoriteTask = new RequestRemoveFavoriteTask(MoviesApplication.getInstance(), aid, "1");
                    mRequestRemoveFavoriteTask.setRequestListener(this);
                    mRequestRemoveFavoriteTask.start();
                }
            }
        } else {
            UIs.showToast(R.string.favorite_failed);
        }
    }

    private void setData() {
        String mReleasedate = video.getReleasedate();
        String formatResult = String.format("%.1f", video.getRating());
        String mCategoryname = video.getCategoryname();
        String mAreaname = video.getAreaname();
        if (!TextUtils.isEmpty(mReleasedate)) {
            String yearText = Utils.getDate(mReleasedate, "yyyy");
            String suffix = (!TextUtils.isEmpty(formatResult)
                    || !TextUtils.isEmpty(mCategoryname)
                    || !TextUtils.isEmpty(mAreaname)) ? "·" : "";
            mYearTxt.setText(yearText + getResources().getString(R.string.year) + suffix);
        }
        if (!TextUtils.isEmpty(formatResult)) {
            String suffix = (!TextUtils.isEmpty(mCategoryname)
                    || !TextUtils.isEmpty(mAreaname)) ? "·" : "";
            mRating.setText(formatResult + getResources().getString(R.string.score) + suffix);
        }
        if (!TextUtils.isEmpty(mCategoryname)) {
            String suffix = (!TextUtils.isEmpty(mAreaname)) ? "·" : "";
            mCategoryTxt.setText(mCategoryname + suffix);
        }
        if (!TextUtils.isEmpty(mAreaname)) {
            mAreaTxt.setText(mAreaname);
        }


        score.setText(formatResult);
        if (MoviesConstant.VT_ZONGYI.equals(video.getVt())) {
            String starrringName = MoviesUtils.optString(
                    video.getStarringname(), "暂无");
            starring.setText((String.format(
                    res.getString(R.string.video_starring_presenter),
                    starrringName)));
        } else {
            String starrringName = MoviesUtils.optString(
                    video.getStarringname(), "暂无");
            starring.setText((String.format(
                    res.getString(R.string.video_starring_actor), starrringName)));
        }
        introduceview.setVideoDataBean(video);
        String yearText = MoviesUtils.optString(video.getReleasedate(), "暂无");
        year.setText((String.format(res.getString(R.string.video_year),
                yearText)));

        String directorText = MoviesUtils.optString(video.getDirectoryname(), "暂无");
        director.setText((String.format(res.getString(R.string.video_director), directorText)));

        PlaySrcList siteList = video.getSrcList();
        // 设置logo(悲催世界siteList为空)
        // 查询播放历史
        playRecordDao = new PlayRecordDao(this);
        playRecord = playRecordDao.getByAid(video.getAid());

        if (null != siteList && null != siteList.getPlaySrcList() && !siteList.getPlaySrcList().isEmpty()) {
            String playSrcTxt = siteList.getPlaySrcList().get(findPositionBySite(playRecord == null ? null : playRecord.getSite(),
                    siteList.getPlaySrcList())).getSitename();
            playSrcTxtTv.setText(playSrcTxt);
            playSrcTips.setText(playSrcTxt);
            LogoImageLoader.getInstance().displayImage(siteList.getPlaySrcList().get(findPositionBySite(playRecord == null ? null : playRecord.getSite(),
                    siteList.getPlaySrcList())).getLogo(),
                    playSrcIconIv, displayoptions, mImageLoadingListener);
        } else {
            playSrcTxtTv.setText(video.getSitename());
            playSrcTips.setText(video.getSitename());
            LogoImageLoader.getInstance().displayImage(video.getLogo(),
                    playSrcIconIv, displayoptions, mImageLoadingListener);
        }
        if (playRecord == null) {
            playRecord = new PlayRecord();
            playRecord.setAid(video.getAid());
        }
        if ("0".equals(porder) || porder == null) {
            porder = playRecord.getPorder();
            mCurrentPlayingPorder = porder;
            pageIndex = playRecord.getPageIndex() <= 0 ? 1 : playRecord.getPageIndex();
            try {
                position = Integer.parseInt(porder) - 1;
            } catch (Exception e) {
                position = -1;
            }
        }
        playRecord.setVt(video.getVt());
        playRecord.setCategoryName(video.getCategoryname());
        if (TextUtils.isEmpty(mTitleTv.getText())) {
            mTitleTv.setText(video.getName());
        }
        playIv.setOnClickListener(new MyOnClickListener());
        mPopPlayImageView.setOnClickListener(new MyOnClickListener());
        mPlayerStatusImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getResources().getText(R.string.play_in_web).equals(mPlayerStatusImage.getText())) {
                    jumpToWebViewPlay(mCurrentPlayPisiotion);
                    PlayDataRecord record = MyDataRecordCreater.build(PlayDataRecord.class);
                    record.setAcode(SelfDataConstant.AC_CLICK);
                    record.setCur_url("half_screen");
                    record.setPlayac(SelfDataConstant.PlAYAC_H5_CMS);
                    record.setSite(getmCrrentSite());
                    RealmDaoManager.addMyDataRecord(record);
                } else if (getResources().getText(R.string.continue_play).equals(mPlayerStatusImage.getText())) {
                    resumePlay();
                } else if (getResources().getText(R.string.play_in_lite).equals(mPlayerStatusImage.getText())) {
                    LiteAppManager.getInstance().launchPlayer(VideoDetailActivity.this, video, mCurrentPlayPisiotion, true, true);
                }
            }
        });
        mWebPageImageView.setOnClickListener(new MyOnClickListener());

    }

    private void setClickable(boolean clickable) {
        mFavoriteImage.setClickable(clickable);
        mShareImage.setClickable(clickable);
        mDownloadImage.setClickable(clickable);
    }


    /**
     * 展示详情页图片右下角的剧集更新信息
     */
    private void setEpisodesData() {
        if (video.getEpisodeList() == null || video.getEpisodeList().size() < 1) {
            episodeDataLl.setVisibility(View.GONE);
            playIv.setVisibility(View.GONE);
            downloadIv.setVisibility(View.GONE);
            mPlayPopLinearLayout.setVisibility(View.GONE);
            mWebPageImageView.setVisibility(View.GONE);
            offlineIv.setVisibility(View.VISIBLE);
            allEpisode.setVisibility(View.GONE);
            mDownloadImage.setVisibility(View.GONE);
            mCanPlayDirectly = false;
            mPlayerStatus.setVisibility(View.VISIBLE);
            mPlayerStatus.setText(R.string.move_be_down);
            setOrientation(false);
            UmengEventPoster.postDefaultPlayState(UmengEventPoster.ALBUM_PLAY_OFF);
            changePlaySrc(0);
            return;
        }
        if ("nets".equals(video.getSubsrc())) {
            //获取清晰度前不可点击
            mDownloadImage.setVisibility(View.GONE);
            mDownloadImage.setImageResource(R.drawable.not_download_icon);
            mDownloadImage.setClickable(false);
            if ("2".equals(mOpenWay)) {
                episodeDataLl.setVisibility(View.GONE);
                playIv.setVisibility(View.GONE);
                downloadIv.setVisibility(View.GONE);
                mPlayPopLinearLayout.setVisibility(View.GONE);
                mWebPageImageView.setVisibility(View.GONE);
                offlineIv.setVisibility(View.VISIBLE);
                allEpisode.setVisibility(View.GONE);
                mDownloadImage.setVisibility(View.GONE);
                mCanPlayDirectly = false;
                mPlayerStatus.setVisibility(View.VISIBLE);
                mPlayerStatus.setText(R.string.move_be_down);
                setOrientation(false);
                UmengEventPoster.postDefaultPlayState(UmengEventPoster.ALBUM_PLAY_OFF);
            } else {
                mPlayPopLinearLayout.setVisibility(View.GONE);
                mWebPageImageView.setVisibility(View.GONE);
                playIv.setVisibility(View.VISIBLE);
                UmengEventPoster.postDefaultPlayState(UmengEventPoster.ALBUM_PLAY);
            }
        } else {
            if ("2".equals(mOpenWay)) {
                playIv.setVisibility(View.GONE);
                mPlayPopLinearLayout.setVisibility(View.GONE);
                mWebPageImageView.setVisibility(View.VISIBLE);
                UmengEventPoster.postDefaultPlayState(UmengEventPoster.ALBUM_PLAY_H5);
            } else {
                mPlayPopLinearLayout.setVisibility(View.VISIBLE);
                mWebPageImageView.setVisibility(View.GONE);
                playIv.setVisibility(View.GONE);
                UmengEventPoster.postDefaultPlayState(UmengEventPoster.ALBUM_PLAY);
            }
        }
        if (video.getVt().equals(MoviesConstant.VT_MOVIE)) {
            episodeDataLl.setVisibility(View.GONE);
        } else if (video.getVt().equals(MoviesConstant.VT_TV)
                || video.getVt().equals(MoviesConstant.VT_CARTOON)) {
            showType="grid";
            episodeTitleTv.setText("剧集");
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            episodeListview.setLayoutManager(linearLayoutManager);
            if (pageIndex >= 1) {
                if (video.getEpisodeList().size() > 5) {
                    allEpisode.setVisibility(View.VISIBLE);
                } else {
                    allEpisode.setVisibility(View.GONE);
                }
                String numEpisodeStr = MoviesUtils.getEpisodeInfo(
                        VideoDetailActivity.this, video);
                moreEpisodeTv.setText(numEpisodeStr);
                moreEpisodeTv.setVisibility(View.VISIBLE);
                episodeListview.setVisibility(View.VISIBLE);
//                varietyListview.setVisibility(View.GONE);
                mEpisodeGridAdapter = new EpisodeGridAdapter(this, video.getEpisodeList(), false);
                episodeListview.setAdapter(mEpisodeGridAdapter);
                mEpisodeGridAdapter.setOnItemClickListener(new EpisodeGridAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position, String porder) {
                        String isPay=video.getEpisodeList().get(position).getIsPay();
                        //付费点击无效
                        if ("1".equals(isPay)) return;
                        //剧集切换 无网提示
                        int netType = NetWorkTypeUtils.reportNetType(VideoDetailActivity.this);
                        if (netType == NetWorkTypeUtils.NETTYPE_NO || netType == NetWorkTypeUtils.TYPE_ERROR) {
                            ToastUtil.showShortToast(VideoDetailActivity.this, getResources().getString(R.string.neterror));
                            return;
                        }

                        mEpisodeGridAdapter.setSelectPosition(position);
                        mCurrentPlayingPorder = porder;
                        setPlayingProcess(false);
                        showNetDialog(position, true);
                        scrollToPosition(0, position, true);
                        mTabs.setCurrentTab(position / 50);
                    }
                });
//                mEpisodeGridAdapter.setSelectPosition(mCurrentPlayPisiotion);
                episodeListview.addOnScrollListener(new RecyclerView.OnScrollListener() {
                    @Override
                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                        super.onScrollStateChanged(recyclerView, newState);
                    }

                    @Override
                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                        super.onScrolled(recyclerView, dx, dy);
                        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                        if (manager.getChildCount() > 0) {
                            int count = manager.getItemCount();
                            int last = ((RecyclerView.LayoutParams) manager
                                    .getChildAt(manager.getChildCount() - 1).getLayoutParams()).getViewAdapterPosition();
                            int first = ((RecyclerView.LayoutParams) manager
                                    .getChildAt(0).getLayoutParams()).getViewAdapterPosition();
                            if (last >= count - 2 && dx >= 0 && !mIsLoading) {
                                currentRequestMoreTime = System.currentTimeMillis();
                                if ((currentRequestMoreTime - lastRequestMoreTime > 3000) || lastRequestMoreSuccessed) {
                                    mIsLoading = true;
                                    requestNeighbour(true);
                                    lastRequestMoreTime = currentRequestMoreTime;
                                }
                            } else if (first <= 1 && dx < 0 && !mIsLoading) {
                                currentRequestMoreTime = System.currentTimeMillis();
                                if ((currentRequestMoreTime - lastRequestMoreTime > 3000) || lastRequestMoreSuccessed) {
                                    mIsLoading = true;
                                    requestNeighbour(false);
                                    lastRequestMoreTime = currentRequestMoreTime;
                                }
                            }
                        }
                    }
                });
            }
            setEpisodesPopupData(video.getEpisodeList(), "grid");
            setEpisodesDownLoadPopupData(video.getEpisodeList(), "grid");
        } else {
            showType="list";
            episodeTitleTv.setText("往期节目");
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            };
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            episodeListview.setLayoutManager(linearLayoutManager);
            if (pageIndex >= 1) {
                moreEpisodeTv.setVisibility(View.GONE);
                ArrayList<Episode> tempList = new ArrayList<Episode>();
                if (video.getEpisodeList().size() > 3) {
                    for (int i = 0; i < 3; i++) {
                        tempList.add(video.getEpisodeList().get(i));
                    }
                } else {
                    tempList = video.getEpisodeList();
                }
                String numEpisodeStr = MoviesUtils.getEpisodeInfo(
                        VideoDetailActivity.this, video);
                moreEpisodeTv.setText(numEpisodeStr);
                moreEpisodeTv.setVisibility(View.VISIBLE);
                mEpisodeListAdapter = new EpisodeListAdapter(this, tempList);
                episodeListview.setAdapter(mEpisodeListAdapter);
                if (video.getEpisodeList().size() <= 3) {
                    allEpisode.setVisibility(View.GONE);
                }
                mEpisodeListAdapter.setOnItemClickListener(new EpisodeGridAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position, String porder) {
                        String isPay=video.getEpisodeList().get(position).getIsPay();
                        //付费点击无效
                        if ("1".equals(isPay)) return;
                        mCurrentPlayingPorder = porder;
                        setPlayingProcess(false);
                        mEpisodeListAdapter.setSelectPosition(position);
                        int realPosition = (mEpisodeListAdapter.getEpisodes().get(position).getPageIndex() - 1) * 50
                                + mEpisodeListAdapter.getEpisodes().get(position).getCurrentPagePosition();
                        showNetDialog(realPosition, false);
                        mTabs.setCurrentTab(mEpisodeListAdapter.getEpisodes().get(position).getPageIndex() - 1);
                    }
                });
                setEpisodesPopupData(video.getEpisodeList(), "list");
                setEpisodesDownLoadPopupData(video.getEpisodeList(), "list");

            }

        }
    }

    /**
     * 切换源事的剧集更新信息
     */
    private void updateEpisodesData() {
        if (video.getEpisodeList() == null || video.getEpisodeList().size() < 1) {
            episodeDataLl.setVisibility(View.GONE);
            playIv.setVisibility(View.GONE);
            downloadIv.setVisibility(View.GONE);
            mPlayPopLinearLayout.setVisibility(View.GONE);
            mWebPageImageView.setVisibility(View.GONE);
            offlineIv.setVisibility(View.VISIBLE);
            allEpisode.setVisibility(View.GONE);
            mDownloadImage.setVisibility(View.GONE);
            mCanPlayDirectly = false;
            mPlayerStatus.setVisibility(View.VISIBLE);
            mPlayerStatus.setText(R.string.move_be_down);
            setOrientation(false);
            changePlaySrc(0);
            UmengEventPoster.postDefaultPlayState(UmengEventPoster.ALBUM_PLAY_OFF);
            return;
        }
        if ("nets".equals(video.getSubsrc())) {
            if ("2".equals(mOpenWay)) {
                episodeDataLl.setVisibility(View.GONE);
                playIv.setVisibility(View.GONE);
                downloadIv.setVisibility(View.GONE);
                mPlayPopLinearLayout.setVisibility(View.GONE);
                mWebPageImageView.setVisibility(View.GONE);
                offlineIv.setVisibility(View.VISIBLE);
                allEpisode.setVisibility(View.GONE);
                mDownloadImage.setVisibility(View.GONE);
                setOrientation(false);
                UmengEventPoster.postDefaultPlayState(UmengEventPoster.ALBUM_PLAY_OFF);
            } else {
                mPlayPopLinearLayout.setVisibility(View.GONE);
                mWebPageImageView.setVisibility(View.GONE);
                playIv.setVisibility(View.VISIBLE);
                UmengEventPoster.postDefaultPlayState(UmengEventPoster.ALBUM_PLAY);
            }
        } else {
            if ("2".equals(mOpenWay)) {
                playIv.setVisibility(View.GONE);
                mPlayPopLinearLayout.setVisibility(View.GONE);
                mWebPageImageView.setVisibility(View.VISIBLE);
                UmengEventPoster.postDefaultPlayState(UmengEventPoster.ALBUM_PLAY_H5);
            } else {
                mPlayPopLinearLayout.setVisibility(View.VISIBLE);
                mWebPageImageView.setVisibility(View.GONE);
                playIv.setVisibility(View.GONE);
                UmengEventPoster.postDefaultPlayState(UmengEventPoster.ALBUM_PLAY);
            }
        }
        if (video.getVt().equals(MoviesConstant.VT_MOVIE)) {
            episodeDataLl.setVisibility(View.GONE);
        } else if (video.getVt().equals(MoviesConstant.VT_TV)
                || video.getVt().equals(MoviesConstant.VT_CARTOON)) {
            episodeTitleTv.setText("选集");
            if (pageIndex >= 1) {
                if (video.getEpisodeList().size() > 5) {
                    allEpisode.setVisibility(View.VISIBLE);
                } else {
                    allEpisode.setVisibility(View.GONE);
                }
                String numEpisodeStr = MoviesUtils.getEpisodeInfo(
                        VideoDetailActivity.this, video);
                moreEpisodeTv.setText(numEpisodeStr);
                moreEpisodeTv.setVisibility(View.VISIBLE);
                episodeListview.setVisibility(View.VISIBLE);
//                varietyListview.setVisibility(View.GONE);
                mEpisodeGridAdapter = new EpisodeGridAdapter(this, video.getEpisodeList(), false);
                mEpisodeGridAdapter.setSelectPosition(-1);
                mEpisodeGridAdapter.notifyDataSetChanged();
                mEpisodeGridAdapter.setOnItemClickListener(new EpisodeGridAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position, String porder) {
                        String isPay=video.getEpisodeList().get(position).getIsPay();
                        //付费点击无效
                        if ("1".equals(isPay)) return;
                        mEpisodeGridAdapter.setSelectPosition(position);
                        mCurrentPlayingPorder = porder;
                        setPlayingProcess(false);
                        showNetDialog(position, true);
                        scrollToPosition(0, position, true);
                        mTabs.setCurrentTab(position / 50);
                    }
                });
                episodeListview.setAdapter(mEpisodeGridAdapter);
            }
            setEpisodesDownLoadPopupData(video.getEpisodeList(), "grid");
            setEpisodesPopupData(video.getEpisodeList(), "grid");
        } else {
            episodeTitleTv.setText("往期节目");
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            };
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            episodeListview.setLayoutManager(linearLayoutManager);
            moreEpisodeTv.setVisibility(View.GONE);
            ArrayList<Episode> tempList = new ArrayList<>();
            if (video.getEpisodeList().size() > 3) {
                for (int i = 0; i < 3; i++) {
                    tempList.add(video.getEpisodeList().get(i));
                }
            } else {
                tempList = video.getEpisodeList();
            }
            String numEpisodeStr = MoviesUtils.getEpisodeInfo(
                    VideoDetailActivity.this, video);
            moreEpisodeTv.setText(numEpisodeStr);
            moreEpisodeTv.setVisibility(View.VISIBLE);
            mEpisodeListAdapter = new EpisodeListAdapter(this, tempList);
            mEpisodeListAdapter.setSelectPosition(-1);
            mEpisodeListAdapter.notifyDataSetChanged();
            if (video.getEpisodeList().size() <= 4) {
                allEpisode.setVisibility(View.GONE);
            }
            mEpisodeListAdapter.setOnItemClickListener(new EpisodeGridAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position, String porder) {
                    String isPay=video.getEpisodeList().get(position).getIsPay();
                    //付费点击无效
                    if ("1".equals(isPay)) return;
                    mCurrentPlayingPorder = porder;
                    setPlayingProcess(false);
                    mEpisodeListAdapter.setSelectPosition(position);
                    int realPosition = (mEpisodeListAdapter.getEpisodes().get(position).getPageIndex() - 1) * 50
                            + mEpisodeListAdapter.getEpisodes().get(position).getCurrentPagePosition();
                    showNetDialog(realPosition, false);
//                    scrollToPosition(mEpisodeListAdapter.getEpisodes().get(position).getPageIndex() - 1,
//                            mEpisodeListAdapter.getEpisodes().get(position).getCurrentPagePosition(), false);
                    mTabs.setCurrentTab(mEpisodeListAdapter.getEpisodes().get(position).getPageIndex() - 1);
                }
            });
            episodeListview.setAdapter(mEpisodeListAdapter);
            setEpisodesPopupData(video.getEpisodeList(), "list");
            setEpisodesDownLoadPopupData(video.getEpisodeList(), "list");
        }
        Episode ep = null;

        if (position != -1 && video.getEpisodeList().size() > position) {
            ep = video.getEpisodeList().get(position);
        } else {
            ep = video.getEpisodeList().get(0);
        }
        if (null != playRecord
                && !(ep.getPorder().equals(playRecord.getPorder()) && video
                .getSubsrc().equals(playRecord.getSite()))) {
            playRecord.setSeekHistory(0);
            playRecord.setPorder(ep.getPorder());
            playRecord.setSite(video.getSubsrc());
        }
        video.setThemeId(mThemeId);
        mPlayData = new PlayData(video, ep.getPorder(),
                playRecord, UmengEventPoster.PLAYER_FROM_DETAIL);
        mPlayData.setmPorderLists(video.getmPorderLists());
        mPlayerControl.setVisibility(View.VISIBLE);
        if (mPlayMediaController == null) {
            mPlayMediaController = new PlayMediaController(VideoDetailActivity.this, mVideoPlayerLayout);
            mPlayMediaController.setmNetClarityListener(VideoDetailActivity.this);
        } else {
            mPlayMediaController.resetPlayData();
        }
        mPlayMediaController.setmPlayData(mPlayData, true, false);
        if (mPlayBackButton.getVisibility() == View.GONE) {
            mPlayBackButton.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 设置剧集信息
     * @param episodeList
     * @param type
     */
    private void setEpisodesDownLoadPopupData(ArrayList<Episode> episodeList, String type) {
        if ("grid".equalsIgnoreCase(type)) {
            mDownLoadEpisodePagerAdapter = new DownLoadEpisodePagerAdapter(getSupportFragmentManager(),
                    this, video, getmCrrentSite(), mEpisodePagerList, true, "halfScreen");
            mDownLoadViewPager.setAdapter(mDownLoadEpisodePagerAdapter);
            mDownLoadViewPager.setOffscreenPageLimit(1);

            String[] titleArr = new String[video.getEpisodePageList().size()];
            for (int i = 0; i < video.getEpisodePageList().size(); i++) {
                titleArr[i] = video.getEpisodePageList().get(i);
            }
            mDownLoadTabs.setViewPager(mDownLoadViewPager, titleArr);
            mDownLoadTabs.setCurrentTab(0);
            if (titleArr.length == 1) {
                mDownLoadTabs.setVisibility(View.GONE);
            }
        } else if ("list".equalsIgnoreCase(type)) {
            String[] titleArr = new String[video.getEpisodePageList().size()];
            for (int i = 0; i < video.getEpisodePageList().size(); i++) {
                titleArr[i] = video.getEpisodePageList().get(i);
            }
            mDownLoadEpisodePagerAdapter = new DownLoadEpisodePagerAdapter(getSupportFragmentManager(), this, video, getmCrrentSite(), mEpisodePagerList, false, "halfScreen");
            mDownLoadViewPager.setAdapter(mDownLoadEpisodePagerAdapter);
            mDownLoadTabs.setViewPager(mDownLoadViewPager, titleArr);
            mDownLoadTabs.setCurrentTab(0);
            if (titleArr.length == 1) {
                mDownLoadTabs.setVisibility(View.GONE);
            }
        } else {

        }

    }


    private void setEpisodesPopupData(ArrayList<Episode> episodeList, String type) {
        if ("grid".equalsIgnoreCase(type)) {
            mEpisodeMapList.put(String.valueOf(pageIndex - 1), video.getPageEpisodeList().get(String.valueOf(pageIndex - 1)));
            mEpisodePagerAdapter = new EpisodePagerAdapter(getSupportFragmentManager(),
                    this, video, getmCrrentSite(), mEpisodePagerList, true, "halfScreen");
            mViewPager.setAdapter(mEpisodePagerAdapter);
            mViewPager.setOffscreenPageLimit(1);

            String[] titleArr = new String[video.getEpisodePageList().size()];
            for (int i = 0; i < video.getEpisodePageList().size(); i++) {
                titleArr[i] = video.getEpisodePageList().get(i);
            }
            mTabs.setViewPager(mViewPager, titleArr);
            mTabs.setCurrentTab(0);
            mTabs.setTextBold(1);
            if (titleArr.length == 1) {
                mTabs.setVisibility(View.GONE);
            }
        } else if ("list".equalsIgnoreCase(type)) {
            mEpisodeMapList.put(String.valueOf(pageIndex - 1), video.getPageEpisodeList().get(String.valueOf(pageIndex - 1)));
            String[] titleArr = new String[video.getEpisodePageList().size()];
            for (int i = 0; i < video.getEpisodePageList().size(); i++) {
                titleArr[i] = video.getEpisodePageList().get(i);
            }
            mEpisodePagerAdapter = new EpisodePagerAdapter(getSupportFragmentManager(), this, video, getmCrrentSite(), mEpisodePagerList, false, "halfScreen");
            mViewPager.setAdapter(mEpisodePagerAdapter);
            mTabs.setViewPager(mViewPager, titleArr);
            mTabs.setCurrentTab(0);
            if (titleArr.length == 1) {
                mTabs.setVisibility(View.GONE);
            }
        } else {

        }

    }

    public static void launch(Activity activity, String aid, String vt,
                              String title, String src, String themeId, String from, String porder, String seid, String bucket) {
        launch(activity, aid, vt, title, src, themeId, from, porder, seid, bucket, false);
    }

    public static void launch(Activity activity, String aid, String vt,
                              String title, String src, String themeId, String from, String porder, String seid, String bucket, boolean isfrompush) {
        Bundle b = new Bundle();
        JumpData jumpData = new JumpData();
        jumpData.setVt(vt == null ? "" : vt);
        jumpData.setAid(aid == null ? "" : aid);
        jumpData.setName(title == null ? "" : title);
        jumpData.setSrc(src == null ? "" : src);
        jumpData.setThemeid(themeId == null ? "" : themeId);
        jumpData.setPorder(porder == null ? "0" : porder);
        jumpData.setSeid(seid == null ? "" : seid);
        jumpData.setBucket(bucket == null ? "" : bucket);
        b.putSerializable(Utils.ALBUM_DATA, jumpData);
        Context context = activity;
        if (context == null) {
            context = MoviesApplication.getInstance();
        }
        Intent intent = new Intent(context, VideoDetailActivity.class);
        intent.putExtras(b);
        intent.putExtra("from", from);
        intent.putExtra(START_FROM_NOTIFICATION, isfrompush);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    public void onRelativeItemClick(View view, int pos) {
        int netType = NetWorkTypeUtils.reportNetType(VideoDetailActivity.this);
        if (netType == NetWorkTypeUtils.NETTYPE_NO || netType == NetWorkTypeUtils.TYPE_ERROR) {
            ToastUtil.showShortToast(VideoDetailActivity.this, getResources().getString(R.string.neterror));
            return;
        }

        // 相关推荐点击
        RelationAlbum relationAlbum = mRelativeList.get(pos);
        Map<String, String> dataMap = BigDataApi.createDataMap("0", "", "0", "-", relationAlbum.getAid(), "-");
        dataMap.put("cur_url", BigDataConstants.PGV_CURRENT_ID_DETAIL + aid);
        dataMap.put("reid", relationAlbum.getReid());
        dataMap.put("bucket", relationAlbum.getBucket());
        BigDataApi.bigDataCommonReport(dataMap, VideoDetailActivity.this);
        RealDataApi.RealDataClickReport(relationAlbum.getReid(), "", relationAlbum.getAid(), "", relationAlbum.getBucket());
        Bundle b = new Bundle();
        JumpData jumpData = new JumpData();
        jumpData.setVt(relationAlbum.getVt() == null ? "" : relationAlbum.getVt());
        jumpData.setAid(relationAlbum.getAid() == null ? "" : relationAlbum.getAid());
        jumpData.setName(relationAlbum.getTitle() == null ? "" : relationAlbum.getTitle());
        jumpData.setSeid(relationAlbum.getReid() == null ? "" : relationAlbum.getReid());
        jumpData.setBucket(relationAlbum.getBucket() == null ? "" : relationAlbum.getBucket());
        b.putSerializable(Utils.ALBUM_DATA, jumpData);
        Intent intent = new Intent(VideoDetailActivity.this, VideoDetailActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtras(b);
        VideoDetailActivity.this.finish();
        if (mPlayMediaController != null) {
            mPlayMediaController.stopTimeCircleReport();
        }
        startActivity(intent);

    }

    private class PlaySrcOnClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            if (mPlaySrcPopup.isShowing()) {
                mPlaySrcPopup.dismiss();
            } else {
                mPlaySrcPopup.showAsDropDown(playSrcIconIv, UIs.dipToPx(5), UIs.dipToPx(5));
            }

//            showDialogBg(mPlaySrcPopup);
        }

    }

    /**
     * 请求剧集信息
     *
     * @author daipei
     */
    private class RequestVideoDataTask extends MoviesHttpAsyncTask<VideoDataBean> {

        private String mFrom = "";

        @Override
        public void netNull() {
            setLoadingFailed();
            super.netNull();
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            setLoadingFailed();
            super.netErr(updateId, errMsg);
        }

        @Override
        public void dataNull(int updateId, String errMsg) {
            setLoadingFailed();
            super.dataNull(updateId, errMsg);
        }

        @Override
        public void codeErr(String code, String msg) {
            setFullScreenOffline();
            super.codeErr(code, msg);
        }

        public RequestVideoDataTask(Context context, String from) {
            super(context);
            mFrom = from;
        }

        @Override
        public LVideoDataHull<VideoDataBean> doInBackground() {
            LVideoDataHull<VideoDataBean> ret = MoviesHttpApi.requestVideoData(
                    new VideoDetailParser(), aid, mFrom);
            if (ret.getDataType() == LVideoDataHull.DataType.DATA_IS_INTEGRITY) {
                VideoDataBean v = ret.getDataEntity();
                if (v.getEpisodeList() != null && v.getEpisodeList().size() != 0) {
                    mCache.put(v.getAid() + v.getSubsrc() + PlayRecord.REQUEST_TYPE_FROM_DETAIL,
                            v.getEpisodeList());
                }
            }
            return ret;
        }

        @Override
        public void onPostExecute(int updateId, VideoDataBean result) {
            video = result;
            if (null != mShareWindow && !TextUtils.isEmpty(result.getPoster())) {
                mShareWindow.setmSharePoster(result.getPoster());
            }
            aid = video.getAid();
            PlaySrcList mPlaySrcList = video.getSrcList();
            setPlaySrcPopData(mPlaySrcList);
            setData();
            if (mPlaySrcList == null || mPlaySrcList.getPlaySrcList() == null || mPlaySrcList.getPlaySrcList().isEmpty()) {
                playSrcLl.setVisibility(View.GONE);
                playIv.setVisibility(View.GONE);
                downloadIv.setVisibility(View.GONE);
                mPlayPopLinearLayout.setVisibility(View.GONE);
                mWebPageImageView.setVisibility(View.GONE);
                offlineIv.setVisibility(View.VISIBLE);
                allEpisode.setVisibility(View.GONE);
                mDownloadImage.setVisibility(View.GONE);
                mCanPlayDirectly = false;
                mPlayerStatus.setVisibility(View.VISIBLE);
                mPlayerStatus.setText(R.string.move_be_down);
                setOrientation(false);
            } else if ("nets".equals(video.getSubsrc())) {
                mPlayPopLinearLayout.setVisibility(View.GONE);
                mWebPageImageView.setVisibility(View.GONE);
                playIv.setVisibility(View.VISIBLE);
            } else {
                mPlayPopLinearLayout.setVisibility(View.VISIBLE);
                mWebPageImageView.setVisibility(View.GONE);
                playIv.setVisibility(View.GONE);
            }
            if (mRequestVideoListTask != null) {
                mRequestVideoListTask.cancel();
            }
            setLoadingComplete();
            if (!TextUtils.isEmpty(getmCrrentSite())) {
                for (int i = 1; i <= pageIndex; i++) {
                    if (getEpisodeMapList() != null && (getEpisodeMapList().get(String.valueOf(i - 1)) == null
                            || getEpisodeMapList().get(String.valueOf(i - 1)).size() <= 0)) {
                        mRequestVideoListTask = new RequestVideoListTask(MoviesApplication.getInstance(), i);
                        mRequestVideoListTask.start();
                    }
                }
            } else {
                video.setEpisodeList(video.getEpisodeList());
                setEpisodesData();
                if (pageIndex == 1) {
                    mDetailRelativeMovieTask = new DetailRelativeMovieTask();
                }
            }

            playRecord.setRequestType(PlayRecord.REQUEST_TYPE_FROM_DETAIL);
            if ("nets".equals(video.getSubsrc())) {// 云盘友盟上报
                CloudDetailReport();
            }
            if (!"".equals(video.getAid()) && !"".equals(mLoginSp.getString(LoginActivity.TOKEN, ""))) {
                mRequestIsAddFavoriteTask = new RequestIsAddFavoriteTask(MoviesApplication.getInstance(), video.getAid(), "1");
                mRequestIsAddFavoriteTask.setRequestListener(VideoDetailActivity.this);
                mRequestIsAddFavoriteTask.start();
            } else {
                if (favoriteDao.isExists(aid)) {
                    isFavorite = true;
                    mFavoriteImage.setImageResource(R.drawable.collection_icon_solid);
                }
            }
        }
    }

    private void setPlaySrcPopData(PlaySrcList result) {
        if (result.getPlaySrcList().size() <= 1) {
            playSrcLl.setVisibility(View.GONE);
            playSrcTips.setClickable(false);
            playSrcIconIv.setClickable(false);
        } else {
            playSrcLl.setVisibility(View.VISIBLE);
            playSrcTips.setClickable(true);
            playSrcIconIv.setClickable(true);
        }
        mPlaySrcList = result;
        popupAdapter = new PlaySrcPopupListAdapter(MoviesApplication.getInstance(),
                mPlaySrcList);
        mSrcListview.setAdapter(popupAdapter);
        // 播放源点击事件
        mSrcListview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long arg3) {
                //播放源切换
                int netType = NetWorkTypeUtils.reportNetType(VideoDetailActivity.this);
                if (netType == NetWorkTypeUtils.NETTYPE_NO || netType == NetWorkTypeUtils.TYPE_ERROR) {
                    ToastUtil.showShortToast(VideoDetailActivity.this, getResources().getString(R.string.neterror));
                    return;
                }
                changePlaySrc(position);
                PlaySrcBean playsrc = popupAdapter.getPlaySrcList().getPlaySrcList().get(position);
                String siteName = playsrc.getSite();
                HashMap<String, String> map = new HashMap<>();
                map.put("siteName", siteName);
                UmengEventPoster.doPost(UmengEventPoster.ARTIFICIAL_WEBSITE, map);
            }
        });
        playSrcLl.setEnabled(true);
    }

    /**
     * 请求播放列表（进入详情页请求播放数据）
     *
     * @author daipei
     */
    private class RequestVideoListTask extends
            MoviesHttpAsyncTask<VideoDataBean> {
        int mIndex;

        public RequestVideoListTask(Context context, int i) {
            super(context);
            mIndex = i;
        }

        @Override
        public void netNull() {
            super.netNull();
            video.setEpisodeList(video.getEpisodeList());
            setEpisodesData();
            if (pageIndex == 1) {
                mDetailRelativeMovieTask = new DetailRelativeMovieTask();
            }
            setLoadingComplete();
            UIs.showToast(R.string.video_playsrc_init_failed);// ???
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
            video.setEpisodeList(video.getEpisodeList());
            setEpisodesData();
            if (pageIndex == 1) {
                mDetailRelativeMovieTask = new DetailRelativeMovieTask();
            }
            setLoadingComplete();
            UIs.showToast(R.string.video_playsrc_init_failed);
        }

        @Override
        public void dataNull(int updateId, String errMsg) {
            super.dataNull(updateId, errMsg);
            video.setEpisodeList(video.getEpisodeList());
            setEpisodesData();
            if (pageIndex == 1) {
                mDetailRelativeMovieTask = new DetailRelativeMovieTask();
            }
            setLoadingComplete();
            UIs.showToast(R.string.video_playsrc_init_failed);
        }

        @Override
        public LVideoDataHull<VideoDataBean> doInBackground() {
            return MoviesHttpApi.requestNewVideoList(new VideoListParser(getmCrrentSite(), video, mIndex), getmCrrentSite(), video.getAid(), mIndex);
        }

        @Override
        public void onPostExecute(int updateId, VideoDataBean result) {
            // 更新srcpop
            if (mEpisodeMapList.size() < pageIndex - 1) {
                mEpisodeMapList.put(String.valueOf(mIndex - 1), result.getPageEpisodeList().get(String.valueOf(mIndex - 1)));
                return;
            }
            mEpisodeMapList.put(String.valueOf(mIndex - 1), result.getPageEpisodeList().get(String.valueOf(mIndex - 1)));
            mPlaySrcList = result.getSrcList();
            List<PlaySrcBean> list = mPlaySrcList.getPlaySrcList();
            for (int i = 0; i < list.size(); i++) {
                String site = list.get(i).getSite();
                if (!StringUtil.isEmpty(site) && (site.equals("letv") || site.equals("nets"))) {
                    int p2pDownload = list.get(i).p2pDownload;
                    SharePreferenceManager.saveVaule(VideoDetailActivity.this, site, (p2pDownload == 0 ? false : true));
                }
            }
            popupAdapter.setList(mPlaySrcList, mCurrentSite);
            mEpisodePagerList = result.getEpisodePageList();
            mIsDownload = result.getIsDownload();
            if ("0".equals(mIsDownload)) {
                mDownloadImage.setImageResource(R.drawable.not_download_icon);
                mDownloadImage.setVisibility(View.GONE);
            } else {
                mDownloadImage.setImageResource(R.drawable.download_icon);
                mDownloadImage.setVisibility(View.VISIBLE);
            }
            mOpenWay = result.getOpenway();
            LogUtils.e(TAG, "mIsDownload is " + mIsDownload);

            // 更新剧集信息
            video.setEpisodeList(getMaximumEpisode(pageIndex));
            if (result.getPlaySrcBean() != null) {
                video.setNowepisodes(result.getPlaySrcBean().getNowEpisode());
            }
            setEpisodesData();
            if (pageIndex == 1) {
                mDetailRelativeMovieTask = new DetailRelativeMovieTask();
            }
            setLoadingComplete();

            // 请求数据自动播放
            playDetailContentRl.setVisibility(View.GONE);
            if (mCanPlayDirectly) {
                mPlayMediaController = new PlayMediaController(VideoDetailActivity.this, mVideoPlayerLayout);
                mPlayMediaController.setmNetClarityListener(VideoDetailActivity.this);
                PlayVideoInSmallScreen(findEpisodeByPorder(porder, video.getEpisodeList()));
                mCanPlayDirectly = false;
                // 清除延时信息
                mHandler.removeMessages(PLAY_CONTROL_ON_RESUME);
            }

        }
    }

    public class SimpleRequestVideoListTask extends MoviesHttpAsyncTask<VideoDataBean> {

        int index;

        public SimpleRequestVideoListTask(Context context, int index) {
            super(context);
            this.index = index;
        }

        @Override
        public void netNull() {
            super.netNull();
            UIs.showToast(R.string.video_playsrc_init_failed);// ???
            lastRequestMoreSuccessed = false;
            mIsLoading = false;
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
            UIs.showToast(R.string.video_playsrc_init_failed);
            lastRequestMoreSuccessed = false;
            mIsLoading = false;
        }

        @Override
        public void dataNull(int updateId, String errMsg) {
            super.dataNull(updateId, errMsg);
            UIs.showToast(R.string.video_playsrc_init_failed);
            lastRequestMoreSuccessed = false;
            mIsLoading = false;
        }

        @Override
        public LVideoDataHull<VideoDataBean> doInBackground() {
            return MoviesHttpApi.requestNewVideoList(new VideoListParser(getmCrrentSite(), video, index), getmCrrentSite(), video.getAid(), index);
        }

        @Override
        public void onPostExecute(int updateId, VideoDataBean result) {
            Log.e("zhaopei", "result is " + result);
            lastRequestMoreSuccessed = true;
            mIsLoading = false;
            refreshVideoEpisode(mEpisodeGridAdapter != null, index - 1, result.getPageEpisodeList().get(String.valueOf(index - 1)));
        }
    }

    public void refreshVideoEpisode(boolean isGrid, int index, ArrayList<Episode> episodeArrayList) {
        if (episodeArrayList != null && episodeArrayList.size() > 0) {
            mEpisodeMapList.put(String.valueOf(index), episodeArrayList);
        }
        ArrayList<Episode> arrayList = getMaximumEpisode(index + 1);
        video.setEpisodeList(arrayList);
        if (isGrid) {
            mEpisodeGridAdapter.setEpisodes(arrayList);
        } else {

        }
        mPlayMediaController.updatePlayData(arrayList);
    }

    public ArrayList<ArrayList<Episode>> getEpisodeList() {
        if (mEpisodeList != null && mEpisodeList.size() >= 0) {
            return mEpisodeList;
        }
        return null;
    }

    public HashMap<String, ArrayList<Episode>> getEpisodeMapList() {
        if (mEpisodeMapList != null && mEpisodeMapList.size() >= 0) {
            return mEpisodeMapList;
        }
        return null;
    }

    public String currentPlayingPorder() {
        return mCurrentPlayingPorder;
    }

    public void setmCurrentPlayingPorder(String porder) {
        mCurrentPlayingPorder = porder;
    }

    public EpisodePlayAdapter getCurrentShowingEpisodePlayAdapter() {
        return mCurrentEpisodePlayAdapter;
    }

    public void setCurrentShowingEpisodePlayAdapter(EpisodePlayAdapter episodePlayAdapter) {
        mCurrentEpisodePlayAdapter = episodePlayAdapter;
    }

    public String currentDownLoadingPorder() {
        return mCurrentDownLoadingPorder;
    }

    public DownloadEpisodePlayAdapter getCurrentShowingEpisodeDownLoadAdapter() {
        return mDownLoadCurrentEpisodePlayAdapter;
    }

    public void setDownloadCurrentShowingEpisodePlayAdapter(DownloadEpisodePlayAdapter episodePlayAdapter) {
        mDownLoadCurrentEpisodePlayAdapter = episodePlayAdapter;
    }


    public void requestNeighbour(boolean loadingNext) {
        if (loadingNext) {
            pageIndex = getNextIndex(pageIndex) >= video.getEpisodePageList().size() ? video.getEpisodePageList().size() :
                    getNextIndex(pageIndex) + 1;
            if (pageIndex <= video.getEpisodePageList().size() && (mEpisodeMapList.get(String.valueOf(pageIndex - 1)) == null
                    || mEpisodeMapList.get(String.valueOf(pageIndex - 1)).size() <= 0)) {
                mSimpleRequestVideoListTask = new SimpleRequestVideoListTask(MoviesApplication.getInstance(), pageIndex);
                mSimpleRequestVideoListTask.start();
            }
        } else {
            pageIndex = getPreIndex(pageIndex) <= 1 ? 1 : getPreIndex(pageIndex) - 1;
            if (pageIndex > 0 && (mEpisodeMapList.get(String.valueOf(pageIndex - 1)) == null
                    || mEpisodeMapList.get(String.valueOf(pageIndex - 1)).size() <= 0)) {
                mSimpleRequestVideoListTask = new SimpleRequestVideoListTask(MoviesApplication.getInstance(), pageIndex);
                mSimpleRequestVideoListTask.start();
            }
        }
    }

    // 获取前一个临近已经加载过页的index
    public int getPreIndex(int currentIndex) {
        if (video == null || video.getEpisodePageList().size() <= 0) {
            return 1;
        }
        int preIndex = currentIndex;
        if (preIndex >= 1 && preIndex <= video.getEpisodePageList().size()) {
            while (preIndex >= 1 && mEpisodeMapList.get(String.valueOf(preIndex - 1)) != null
                    && mEpisodeMapList.get(String.valueOf(preIndex - 1)).size() > 0) {
                preIndex--;
            }
            return preIndex + 1;
        }
        return 1;
    }

    // 获取下一个临近已经加载的页的index
    public int getNextIndex(int currentIndex) {
        if (video == null || video.getEpisodePageList().size() <= 0) {
            return 1;
        }
        int nextIndex = currentIndex;
        if (nextIndex >= 1 && nextIndex <= video.getEpisodePageList().size()) {
            while (nextIndex >= 1 && mEpisodeMapList.get(String.valueOf(nextIndex - 1)) != null
                    && mEpisodeMapList.get(String.valueOf(nextIndex - 1)).size() > 0) {
                nextIndex++;
            }
            if (nextIndex > video.getEpisodePageList().size()) {
                return video.getEpisodePageList().size();
            }
            return nextIndex - 1;
        }
        return video.getEpisodePageList().size();
    }

    public ArrayList<Episode> getMaximumEpisode(int index) {
        ArrayList<Episode> arrayList = new ArrayList<>();
        int preIndex = getPreIndex(index);
        int nextIndex = getNextIndex(index);
        for (int i = preIndex; i <= nextIndex; i++) {
            arrayList.addAll(mEpisodeMapList.get(String.valueOf(i - 1)));
        }
        return arrayList;
    }

    public void scrollToPosition(int pageIndex, int position, boolean isGrid) {
        if (isGrid) {
            episodeListview.scrollToPosition(pageIndex * 50 + position);
        } else {
            ArrayList<Episode> tempList = new ArrayList<>();
            int index = 0;
            if (video.getEpisodeList().size() > 3) {
                if (video.getEpisodeList().size() >= position + pageIndex * 50 + 3) {
                    for (int i = position + pageIndex * 50; i < video.getEpisodeList().size() &&
                            i < position + pageIndex * 50 + 3; i++) {
                        tempList.add(video.getEpisodeList().get(i));
                    }
                    index = 0;
                } else {
                    for (int j = video.getEpisodeList().size() - 3; j < video.getEpisodeList().size(); j++) {
                        tempList.add(video.getEpisodeList().get(j));
                    }
                    index = position + pageIndex * 50 + 3 - video.getEpisodeList().size();
                }
            } else {
                tempList = video.getEpisodeList();
            }
            mEpisodeListAdapter.setEpisodes(tempList);
            mEpisodeListAdapter.setSelectPosition(index);
        }
    }

    private int findEpisodeByPorder(String porder, ArrayList<Episode> episodes) {
        if (episodes == null) {
            return 0;
        }
        for (int i = 0; i < episodes.size(); i++) {
            Episode episode = episodes.get(i);
            LogUtils.e("TAG", "current is " + i + " " + episode.getPorder());
            if (porder != null && porder.equals(episode.getPorder())) {
                LogUtils.e("TAG", "currenta is " + i);
                return i;
            }
        }
        return 0;
    }

    private int findPositionBySite(String site, List<PlaySrcBean> srcList) {
        if (TextUtils.isEmpty(site) || srcList == null) {
            if (srcList != null && srcList.size() > 0) {
                if (popupAdapter != null) {
                    popupAdapter.setSelectPosition(srcList.get(0).getSite());
                }
            }
            return 0;
        }
        for (int i = 0; i < srcList.size(); i++) {
            PlaySrcBean src = srcList.get(i);
            if (!TextUtils.isEmpty(site) && site.equals(src.getSite())) {
                if (popupAdapter != null) {
                    popupAdapter.setSelectPosition(site);
                }
                return i;
            }
        }
        return 0;
    }

    public boolean updatePlayPageInWorkMobile() {
        if ((NetWorkTypeUtils.getNetType() == NetWorkTypeUtils.NETTYPE_3G || NetWorkTypeUtils.getNetType()
                == NetWorkTypeUtils.NETTYPE_2G || NetWorkTypeUtils.getNetType()
                == NetWorkTypeUtils.NETTYPE_4G)) {
            if (MoviesConstant.isIn4GPlayVideo) {
                //用来控制只要开启到关闭app的这个过程确认过在非wifi下继续播放，则之后都默认播放
                ToastUtil.showShortToast(this, getResources().getString(R.string.new_wireless_tip));
                return false;
            }
            if (MoviesConstant.isFirstIn4GPlayVideo) {
                return true;
            } else {
                ToastUtil.showShortToast(this, getResources().getString(R.string.new_wireless_tip));
                return false;
            }
        } else if (NetWorkTypeUtils.getNetType() == NetWorkTypeUtils.NETTYPE_WIFI) {
            MoviesConstant.isFirstIn4GPlayVideo = true;
        }
        return false;
    }

    /**
     * 播放源列表点击请求播放源列表数据
     */
    private class RequestPlaySrcDetailTask extends
            MoviesHttpAsyncTask<VideoDataBean> {
        @Override
        public boolean onPreExecute() {
            mProgressDialog.show();
            mPlaySrcPopup.dismiss();
            UIs.showOrHideBg(dialogBgRl, false);
            return super.onPreExecute();
        }

        @Override
        public void dataNull(int updateId, String errMsg) {
            mProgressDialog.dismiss();
            UIs.showToast(R.string.video_playsrc_init_failed);
            super.dataNull(updateId, errMsg);
        }

        @Override
        public void netNull() {
            super.netNull();
            mProgressDialog.dismiss();
            UIs.showToast(R.string.video_playsrc_init_failed);
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
            mProgressDialog.dismiss();
            UIs.showToast(R.string.video_playsrc_init_failed);
        }

        private String site;

        public RequestPlaySrcDetailTask(Context context, String site) {
            super(context);
            this.site = site;
        }

        @Override
        public LVideoDataHull<VideoDataBean> doInBackground() {
            pageIndex = 1;
            LVideoDataHull<VideoDataBean> dataHull = MoviesHttpApi.requestVideoList(new VideoListParser(site, video, pageIndex), site, video.getAid(), pageIndex, pageSize);
            if (dataHull.getDataType() == LVideoDataHull.DataType.DATA_IS_INTEGRITY) {
                PlaySrcBean p = dataHull.getDataEntity().getPlaySrcBean();
                if (p.getEpisodes() != null && p.getEpisodes().size() != 0) {
                    mCache.put(video.getAid() + p.getSite()
                                    + PlayRecord.REQUEST_TYPE_FROM_WEBSITE,
                            p.getEpisodes());
                }
            }
            return dataHull;
        }

        @Override
        public void onPostExecute(int updateId, VideoDataBean vidoBean) {
            // 更新srcpop
            mEpisodePagerList = vidoBean.getEpisodePageList();
            mPlaySrcList = vidoBean.getSrcList();
            popupAdapter.setList(mPlaySrcList, site);
            PlaySrcBean result = vidoBean.getPlaySrcBean();
            mProgressDialog.dismiss();
            if (result.getEpisodes().size() == 0) {
                UIs.showToast(R.string.video_playsrc_init_failed);
                return;
            }
            playSrcTxtTv.setText(result.getSitename());
            playSrcTips.setText(result.getSitename());
            // 设置logo
            LogoImageLoader.getInstance().displayImage(result.getLogo(),
                    playSrcIconIv, displayoptions,
                    mImageLoadingListener);

            mIsDownload = result.getIsDownload();
            if ("0".equals(mIsDownload)) {
                mDownloadImage.setImageResource(R.drawable.not_download_icon);
                mDownloadImage.setVisibility(View.GONE);
            } else {
                mDownloadImage.setImageResource(R.drawable.download_icon);
                mDownloadImage.setVisibility(View.VISIBLE);
            }
            mOpenWay = result.getOpenway();
            LogUtils.e(TAG, "mIsDownload is " + mIsDownload);

            video.setEpisodeList(result.getEpisodes());// 取到对应源的播放数据
            video.setUrl(result.getEpisodes().get(0).getPlay_url());
            video.setSubsrc(result.getSite());
            video.setNowepisodes(result.getNowEpisode());
            video.setEpisodes(result.getEpisodeNum());
            video.setSitename(result.getSitename());
            updateEpisodesData();
            playIv.setOnClickListener(new MyOnClickListener());
            playRecord.setRequestType(PlayRecord.REQUEST_TYPE_FROM_WEBSITE);
        }
    }

    private class MyOnClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.iv_popup_webpage_play:
                    jumpToWebViewPlay(0);
                    break;
                case R.id.iv_webpage_play:
                    jumpToWebViewPlay(0);
                    break;
                default:
                    showNetDialog(0, true);
            }
        }
    }

    /**
     * 显示网络对话框
     */
    public void showNetDialog(int position, boolean isGridView) {
        VideoDetailActivity.this.position = position;
        int netType = NetWorkTypeUtils.getNetType();
        switch (netType) {
            case NetWorkTypeUtils.NETTYPE_NO:
                ToastUtil.showShortToast(this, R.string.neterror);
                break;
            case NetWorkTypeUtils.NETTYPE_WIFI:
                if (mPlaySrcList != null && mPlaySrcList.getPlaySrcList() != null &&
                        mPlaySrcList.getPlaySrcList().size() > 0) {
                    playVideo(position, isGridView);
                }
                break;
            case NetWorkTypeUtils.NETTYPE_2G:
//                DialogUtil.getInstance(VideoDetailActivity.this).checkMobileNetDialog(VideoDetailActivity.this, position, isGridView);
                if (mPlaySrcList != null && mPlaySrcList.getPlaySrcList() != null &&
                        mPlaySrcList.getPlaySrcList().size() > 0) {
                    playVideo(position, isGridView);
                }
                break;
            case NetWorkTypeUtils.NETTYPE_3G:
//                DialogUtil.getInstance(VideoDetailActivity.this).checkMobileNetDialog(VideoDetailActivity.this, position, isGridView);
                if (mPlaySrcList != null && mPlaySrcList.getPlaySrcList() != null &&
                        mPlaySrcList.getPlaySrcList().size() > 0) {
                    playVideo(position, isGridView);
                }
                break;
            case NetWorkTypeUtils.NETTYPE_4G:
//                DialogUtil.getInstance(VideoDetailActivity.this).checkMobileNetDialog(VideoDetailActivity.this, position, isGridView);
                if (mPlaySrcList != null && mPlaySrcList.getPlaySrcList() != null &&
                        mPlaySrcList.getPlaySrcList().size() > 0) {
                    playVideo(position, isGridView);
                }
                break;
        }
    }

    public void playVideo(int position, boolean isGridView) {
        if (video != null) {
            if (mPlayMediaController != null) {
                mPlayMediaController.PlayEpisode(position, isGridView);
            }
        }
    }

    public void IntentToPlayActivitySelfOwn(int position) {
        if (video != null && video.getEpisodeList().size() > 0) {
            Episode ep = video.getEpisodeList().get(position);
            // 如果播放信息与播放记录不一致，则更新播放记录
            if (null != playRecord
                    && !(ep.getPorder().equals(playRecord.getPorder()) && video
                    .getSubsrc().equals(playRecord.getSite()))) {
                playRecord.setSeekHistory(0);
                playRecord.setPorder(ep.getPorder());
                playRecord.setSite(video.getSubsrc());
            }
            Intent intent = new Intent(VideoDetailActivity.this,
                    PlayActivitySelfOwn.class);
            intent.putExtra("mIsHalfScreen", true);
            Bundle bundle = new Bundle();
            video.setThemeId(mThemeId);
            PlayData playData = new PlayData(video, ep.getPorder(),
                    playRecord, UmengEventPoster.PLAYER_FROM_DETAIL);
            playData.setmPorderLists(video.getmPorderLists());
            bundle.putSerializable(Utils.PLAY_DATA, playData);
            bundle.putBoolean(Utils.PLAY_3G_NET, mIsWifiTo3GFlag);
            intent.putExtras(bundle);
            VideoDetailActivity.this.startActivity(intent);
            mIsWifiTo3GFlag = false;
        }

    }

    public void PlayVideoInSmallScreen(int position) {
        mCurrentPlayPisiotion = position;
        setFullScreen(false, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        if (video != null && video.getEpisodeList().size() > 0) {
            final Episode ep = video.getEpisodeList().get(position);
            // 如果播放信息与播放记录不一致，则更新播放记录
            if (null != playRecord
                    && !(ep.getPorder().equals(playRecord.getPorder()) && video
                    .getSubsrc().equals(playRecord.getSite()))) {
                playRecord.setSeekHistory(0);
                playRecord.setPorder(ep.getPorder());
                playRecord.setSite(video.getSubsrc());
            }
            mCurrentPlayingPorder = ep.getPorder();
            video.setThemeId(mThemeId);
            if (!TextUtils.isEmpty(getmCurrentSiteName())) {
                video.setSitename(getmCurrentSiteName());
            }
            mPlayData = new PlayData(video, ep.getPorder(),
                    playRecord, UmengEventPoster.PLAYER_FROM_DETAIL);
            mPlayData.setmPorderLists(video.getmPorderLists());
            mPlayerControl.setVisibility(View.VISIBLE);
            mPlayMediaController.setmPlayData(mPlayData, true, true);
            mPlayMediaController.onResume();
            mIsWifiTo3GFlag = false;
            updateEpisodeStatus(position);
            if (mEpisodeListAdapter != null || mEpisodeGridAdapter != null) {
                mHander.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        scrollToPosition(ep.getPageIndex() - 1, ep.getCurrentPagePosition(), mEpisodeGridAdapter != null);
                    }
                }, 500);
            }
        }
    }

    public void updateEpisodeStatus(int position) {
        if (mEpisodeGridAdapter != null && position < video.getEpisodeList().size()) {
            mCurrentPlayingPorder = video.getEpisodeList().get(position).getPorder();
            mEpisodeGridAdapter.setSelectPosition(position);
            scrollToPosition(video.getEpisodeList().get(position).getPageIndex() - 1,
                    video.getEpisodeList().get(position).getCurrentPagePosition(), true);
        }
        if (mEpisodeListAdapter != null && position < video.getEpisodeList().size()) {
            mCurrentPlayingPorder = video.getEpisodeList().get(position).getPorder();
            int p = listAdapterPosition(position);
            if (p >= 0) {
                mEpisodeListAdapter.setSelectPosition(p);
            } else {
                scrollToPosition(video.getEpisodeList().get(position).getPageIndex() - 1,
                        video.getEpisodeList().get(position).getCurrentPagePosition(), false);
            }
        }
        if (getCurrentShowingEpisodePlayAdapter()!=null&&position < video.getEpisodeList().size()){
            mCurrentPlayingPorder = video.getEpisodeList().get(position).getPorder();
            getCurrentShowingEpisodePlayAdapter().setmSelectProder(mCurrentPlayingPorder);
            getCurrentShowingEpisodePlayAdapter().notifyDataSetChanged();
        }

        if (isLastEpisodeAndNeedToReuqest(position)) {
            requestNeighbour(true);
        }
    }

    public int listAdapterPosition(int realPosition) {
        Episode episode = video.getEpisodeList().get(realPosition);
        ArrayList<Episode> episodes = mEpisodeListAdapter.getEpisodes();
        for (int i = 0; episodes.size() >= 0 && i < episodes.size(); i++) {
            if (episodes.get(i).getPorder().equals(episode.getPorder())) {
                return i;
            }
        }
        return -1;
    }

    public boolean isLastEpisodeAndNeedToReuqest(int position) {
        if (video != null && video.getEpisodeList().size() - 1 == position &&
                video.getEpisodePageList().size() > video.getEpisodeList().get(position).getPageIndex()) {
            return true;
        }
        return false;
    }

    public void setFullScreenByClick(boolean isFull, int orientation) {
        mHandler.removeMessages(LANDSCAPE_REVERSE);
        mHandler.removeMessages(LANDSCAPE);
        mHandler.removeMessages(PORTRAIT);
        if (isFull) {
            mClickInPort = true;
        } else {
            mClickInLand = true;
        }
        setFullScreen(isFull, orientation);
    }

    // 竖屏方向暂只设置为 SCREEN_ORIENTATION_PORTRAIT，和orientation无关
    public void setFullScreen(boolean isFull, int orientation) {
        mIsHalfScreen = !isFull;
        if (mPlayMediaController == null) {
            return;
        }
        if (isFull) {
            dismissAllPopWindow();
            setRequestedOrientation(orientation);
            if (episodeDataLl != null) {
                episodeDataLl.setVisibility(View.GONE);
            }
            if (relativeRecommendLl != null) {
                relativeRecommendLl.setVisibility(View.GONE);
            }
            int windowWidth = Utils.getWidthPixels(this);
            int windowHeight = Utils.getHeightPixels(this);
            int temp;
            if (windowWidth < windowHeight) {
                temp = windowWidth;
                windowWidth = windowHeight;
                windowHeight = temp;
            }
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)mVideoPlayerLayout.getLayoutParams();
            params.width = windowWidth;
            params.height = windowHeight;
            mVideoPlayerLayout.setLayoutParams(params);
            mPlayMediaController.setPlayMediaControlView(mVideoPlayerLayout);
            mPlayMediaController.setHalfScreenView(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().setNavigationBarColor(getResources().getColor(R.color.black));
            }
            hadFullScreen = true;
        } else {
            if (mHandler != null) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (scrollView != null) {
                            scrollView.scrollTo(0, 0);
                        }
                    }
                }, 300);
            }
            setRequestedOrientation(orientation);
            if (episodeDataLl != null && video != null &&
                    !MoviesConstant.VT_MOVIE.equals(video.getVt())) {
                episodeDataLl.setVisibility(View.VISIBLE);
            }
            if (relativeRecommendLl != null && mRelativeList != null) {
                relativeRecommendLl.setVisibility(View.VISIBLE);
            }
            int windowWidth = Utils.getWidthPixels(this);
            int windowHeight = Utils.getHeightPixels(this);
            int temp;
            if (windowWidth > windowHeight) {
                temp = windowWidth;
                windowWidth = windowHeight;
                windowHeight = temp;
            }
            int height = (windowWidth * windowWidth) / windowHeight;
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)mVideoPlayerLayout.getLayoutParams();
            params.width = windowWidth;
            params.height = height;
            mVideoPlayerLayout.setLayoutParams(params);
            mPlayMediaController.setPlayMediaControlView(mVideoPlayerLayout);
            mPlayMediaController.setHalfScreenView(false);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().setNavigationBarColor(mNavigationBarColor);
            }
            if(hadFullScreen){
                EventBus.getDefault().post(new MyMessageEvent(MyMessageEvent.USE_BAIDUCHECK_METHOD));
            }
        }
    }

    public void setOrientation(boolean enable) {
        if (mOrientationListener != null) {
            if (enable) {
                mOrientationListener.enable();
            } else {
                mHandler.removeMessages(LANDSCAPE_REVERSE);
                mHandler.removeMessages(LANDSCAPE);
                mHandler.removeMessages(PORTRAIT);
                mOrientationListener.disable();
            }
        }
    }

    public void jumpToWebViewPlay(int position) {
        UMengReport mUMengReport = new UMengReport();
        mUMengReport.setStartLoadingTime(System.currentTimeMillis());
        mUMengReport.setAid(video.getAid());
        mUMengReport.setName(video.getName());
        if (video.getVid() == null) {
            mUMengReport.setVid("");
        } else {
            mUMengReport.setVid(video.getVid());
        }
        mUMengReport.setCategoryName(video.getCategoryname());
        // 判断
        String from = MoviesApplication.getInstance().getLastPageClassName();
        mUMengReport.setFrom(from);
        mUMengReport.setIsUserH5("Yes");
        mUMengReport.setPlayresult(UmengEventPoster.PLAYER_RESULT_FAILED);
        UmengEventPoster.postPlayer(mUMengReport);
        Intent intent = new Intent(VideoDetailActivity.this, PlayActivityFroWebView.class);
        if (position < video.getEpisodeList().size()) {
            intent.putExtra("url", video.getEpisodeList().get(position).getPlay_url());
        }
        intent.putExtra("title", video.getName());
        intent.putExtra("site",video.getSubsrc());
        this.startActivity(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mPlayData != null) {
            UmengEventPoster.postWatchTime(mPlayData.getmViewName(), MoviesApplication.getInstance().getLastPageClassName(),
                    mPlayData.getCategoryName(), (int) (System.currentTimeMillis() - mCurrentTime) / 1000);
        }
        MobclickAgent.onPause(this);
        if (containerLayout != null) {
            containerLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    PlayerUtils.sendNotPlayingBroadcast(VideoDetailActivity.this);
                }
            }, 2000);
        }
        // 停止播放器页面刷新
        if (null != mPlayMediaController) {
            mPlayMediaController.onPause();
        }
        setOrientation(false);
        dismissAllPopWindow();
        if (mPlayMediaController != null) {
            mPlayMediaController.LetvPlayerStatistics(Constants.LETV_PLAY_ACT_ON_PAUSE);
        }
        downLoadManager.deregisterDownloadObserver(this);
    }

    private boolean dismissAllPopWindow() {
        if (null != mIntroPopup && mIntroPopup.isShowing()) {
            mIntroPopup.dismiss();
            UIs.showOrHideBg(dialogBgRl, false);
            return true;
        }
        if (null != mPlaySrcPopup && mPlaySrcPopup.isShowing()) {
            mPlaySrcPopup.dismiss();
            UIs.showOrHideBg(dialogBgRl, false);
            return true;
        }
        if (null != mEpisodePopup && mEpisodePopup.isShowing()) {
            mEpisodePopup.dismiss();
            UIs.showOrHideBg(dialogBgRl, false);
            return true;
        }
        if (null != mDownloadPopup && mDownloadPopup.isShowing()) {
            mDownloadPopup.dismiss();
            UIs.showOrHideBg(dialogBgRl, false);
            return true;
        }
        if (null != mShareWindow && mShareWindow.isShowing()) {
            mShareWindow.dissMissPopupWindow();
            return true;
        }
        if (null != mLoginPopupWindow && mLoginPopupWindow.isShowing()) {
            mLoginPopupWindow.dissMissPopupWindow();
            return true;
        }
        if (mRelativeLayout != null && mRelativeLayout.getVisibility() == View.VISIBLE) {
            hideEpisodeFragment();
            return true;
        }
        if (mDownLoadRelativeLayout != null && mDownLoadRelativeLayout.getVisibility() == View.VISIBLE) {
            mDownLoadRelativeLayout.setAnimation(AnimationUtils.loadAnimation(VideoDetailActivity.this, R.anim.dialog_push_out));
            mDownLoadRelativeLayout.setVisibility(View.GONE);
            setClickable(true);
            return true;
        }
        return false;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        fromBackground = true;
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mLastFromClass = MoviesApplication.getInstance().getLastPageClassName();
        requestMarqueenAd();
        if(isBackToForeGround) {
            mShakeAd.requestShakeAd(MoviesHttpApi.DETAIL_SHAKE);
            isBackToForeGround = false;
        }

        mCurrentTime = System.currentTimeMillis();
        updateDownloadedEpisodesNum(downLoadManager);
        mDetailAdData = null;
        requestAdData();// 请求广告数据
        if (mCurrentPopup != null && mCurrentPopup.isShowing()) {
            UIs.showOrHideBg(dialogBgRl, true);
        } else {
            UIs.showOrHideBg(dialogBgRl, false);
        }
        MobclickAgent.onResume(this);
        setOrientation(true);
        mHandler.sendEmptyMessageDelayed(PLAY_CONTROL_ON_RESUME, 1000);
        if (mPlayMediaController != null) {
            mPlayMediaController.LetvPlayerStatistics(Constants.LETV_PLAY_ACT_ON_RESUME);
        }
        downLoadManager.registerDownloadObserver(this);
        if (isFirstRequestRecomAd) {
            requestAdRecom();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        fromBackground = false;
        ToastUtil.cancelToast();
        setWifiTo3GFlag(false);
        unregisterCheckNetwork();
        if (MoviesApplication.getInstance().getVideoDetailActivity() == this) {
            MoviesApplication.getInstance().setVideoDetailActivity(null);
        }
        if (mOrientationListener != null) {
            mOrientationListener.disable();
        }
        if (mPlayMediaController != null) {
            mPlayMediaController.setmNetClarityListener(null);
            mPlayMediaController.onDestroy();
        }
        mPlayMediaController = null;
        if (mDetailRelativeMovieTask != null) {
            mDetailRelativeMovieTask.cancel();
            mDetailRelativeMovieTask = null;
        }
        if (mRequestVideoListTask != null) {
            mRequestVideoListTask.cancel();
            mRequestVideoListTask = null;
        }
        if (mRequestIsAddFavoriteTask != null) {
            mRequestIsAddFavoriteTask.cancel();
            mRequestIsAddFavoriteTask.setRequestListener(null);
            mRequestIsAddFavoriteTask = null;
        }
        if (requestTask != null) {
            requestTask.cancel();
            requestTask = null;
        }
        if (mRequestAdTask != null) {
            mAdRequestResultListener = null;
            mRequestAdTask.cancel();
            mRequestAdTask = null;
        }
        if (mSimpleRequestVideoListTask != null) {
            mSimpleRequestVideoListTask.cancel();
            mSimpleRequestVideoListTask = null;
        }
        if (requestPlaySrcDetail != null) {
            requestPlaySrcDetail.cancel();
            requestPlaySrcDetail = null;
        }
    }

    private ImageLoadingListener mImageLoadingListener = new ImageLoadingListener() {

        @Override
        public void onLoadingStarted(String arg0, View arg1) {
        }

        @Override
        public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
        }

        @Override
        public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
        }

        @Override
        public void onLoadingCancelled(String arg0, View arg1) {
        }
    };

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    public void refreshToH5(int position, String strStatusImage, String strStatus, boolean isShowStatusImg) {
        mCurrentPlayPisiotion = position;
        if (isShowStatusImg) {
            mPlayerStatusImage.setVisibility(View.VISIBLE);
        } else {
            mPlayerStatusImage.setVisibility(View.GONE);
        }
        mPlayStatus.setVisibility(View.VISIBLE);
        mPlayerStatusImage.setText(strStatusImage);
        mPlayerStatus.setVisibility(View.VISIBLE);
        mPlayerStatus.setText(strStatus);
        if (mIsHalfScreen) {
            setOrientation(false);
        }
    }

    public void refreshToPlayError() {
        int netType = NetWorkTypeUtils.reportNetType(MoviesApplication.getInstance());
        if (netType == NetWorkTypeUtils.NETTYPE_NO || netType == NetWorkTypeUtils.TYPE_ERROR) {

            if (mPlayMediaController != null) {
                mPlayMediaController.mobileNetNeedPause();  //手动暂停播放
            }
            reFreshToNoNet();
        } else {
            mPlayerStatusImage.setVisibility(View.GONE);
            mPlayerStatusImage.setText(R.string.play_in_web);
            mPlayerStatus.setVisibility(View.VISIBLE);
            mPlayerStatus.setText(R.string.play_error);
        }
        if (mIsHalfScreen) {
            setOrientation(false);
        }
    }

    public void reFreshToNoNet() {
        mPlayerStatusImage.setVisibility(View.GONE);
        mPlayerStatus.setVisibility(View.VISIBLE);
        mPlayerStatus.setText(R.string.no_net);
        mPlayBackButton.setVisibility(View.VISIBLE);
    }

    public void refreshToMobileNet() {
        mPlayerStatusImage.setVisibility(View.VISIBLE);
        mPlayerStatusImage.setText(R.string.continue_play);
        mPlayerStatus.setVisibility(View.VISIBLE);
        mPlayerStatus.setText(R.string.play_in_mobile_des);
        mlyBtnPlayWeb.setVisibility(View.GONE);
    }

    public void setPlayingProcess(boolean isPlayingProcess) {
        mIsPlayingProcess = isPlayingProcess;
    }

    public boolean getPlayingProcess() {
        return mIsPlayingProcess;
    }

    @Override
    public boolean onRefreshPlayerListener(int position) {
        // 更新播放器的相关状态
        mRetryLinearLayout.setVisibility(View.GONE);
        if (mEpisodeGridAdapter != null) {
            mEpisodeGridAdapter.setSelectPosition(position);
        }
        mCurrentPlayPisiotion = position;
        if (updatePlayPageInWorkMobile()) {
            mCanPlayDirectly = false;
            refreshToMobileNet();
            return false;
        } else if (video != null && LiteAppManager.getInstance().launchPlayer(VideoDetailActivity.this, video, findEpisodeByPorder(porder, video.getEpisodeList()), true, false)) {
            mCanPlayDirectly = false;
            mPlayerStatusImage.setVisibility(View.VISIBLE);
            mPlayerStatusImage.setText(R.string.play_in_lite);
            mPlayerStatus.setVisibility(View.VISIBLE);
            mPlayerStatus.setText(R.string.play_in_lite_des);
            if (mIsHalfScreen) {
                setOrientation(false);
            }
            mlyBtnPlayWeb.setVisibility(View.GONE);
            return false;
        } else if (mPlaySrcList != null && mPlaySrcList.getPlaySrcList() != null &&
                mPlaySrcList.getPlaySrcList().size() > 0 && !"nets".equals(video.getSubsrc())) {
            if ("2".equals(mOpenWay)) {
                mCanPlayDirectly = false;
                mPlayerStatusImage.setVisibility(View.VISIBLE);
                mPlayerStatusImage.setText(R.string.play_in_web);
                mPlayerStatus.setVisibility(View.VISIBLE);
                mPlayerStatus.setText(R.string.play_in_web_des);
                if (mIsHalfScreen) {
                    setOrientation(false);
                }
                UmengEventPoster.postDefaultPlayState(UmengEventPoster.ALBUM_PLAY_H5);
                mlyBtnPlayWeb.setVisibility(View.GONE);
                return false;
            } else if (Constants.TAG_IQIYI_SDK.equals(video.getSubsrc()) && Constants.SDK_IQIYI.equals(mPlayData.getPlayer())) {
                mCanPlayDirectly = false;
                if(mPlayMediaController != null && mPlayMediaController.mRetryLinearLayout != null){
                    mPlayMediaController.mRetryLinearLayout.setVisibility(View.GONE);
                }
                mPlayerStatusImage.setVisibility(View.GONE);
                mPlayerStatus.setVisibility(View.GONE);
                mlyBtnPlayWeb.setVisibility(View.VISIBLE);
                if (mIsHalfScreen) {
                    setOrientation(false);
                }
                return false;
            } else if (video.getEpisodeList().size() > position && "1".equals(video.getEpisodeList().get(position).getIsPay())) {
                refreshToH5(position, this.getResources().getString(R.string.play_in_web),
                        this.getResources().getString(R.string.play_vip_des),false);
                return false;
            } else {
                setOrientation(true);
                mPlayerStatusImage.setVisibility(View.GONE);
                mPlayerStatus.setVisibility(View.GONE);
            }
        }
        setOrientation(true);
        mPlayerStatusImage.setVisibility(View.GONE);
        mPlayerStatus.setVisibility(View.GONE);
        mlyBtnPlayWeb.setVisibility(View.GONE);
        return true;
    }

    public String getVideoTitle() {
        return videoTitle;
    }

    public VideoDataBean getVideo() {
        video.setSeid(seid == null ? "" : seid);
        video.setBucket(bucket == null ? "" : bucket);
        return video;
    }

    private String getQzoneTitle(String name) {
        StringBuffer titleBuff = new StringBuffer();
        titleBuff.append(getString(R.string.qzonshare_1));
        titleBuff.append("<<");
        titleBuff.append(name);
        titleBuff.append(">>");
        titleBuff.append(getString(R.string.qzoneshare_2));
        return titleBuff.toString();
    }

    public Bitmap getRes(String name) {
        ApplicationInfo appInfo = getApplicationInfo();
        int resID = getResources().getIdentifier(name, "drawable",
                appInfo.packageName);
        return BitmapFactory.decodeResource(getResources(), resID);
    }

    /**
     * qinguoli 注册监听手机网络广播 接收
     */
    protected void registerCheckNetwork() {
        mCheckReceiver = new NetworkCheckReceiver();
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction(PlayerUtils.CONNECTIVTY_CHANGE);
        intentfilter.addAction(Utils.SDCARD_NOSPACE_ACTION);
        this.registerReceiver(mCheckReceiver, intentfilter);
    }

    /**
     * qinguoli 取消对网络变化的监听*
     */
    protected void unregisterCheckNetwork() {
        if (mCheckReceiver != null) {
            try {
                this.unregisterReceiver(mCheckReceiver);
            } catch (IllegalArgumentException e) {
                if (e.getMessage().contains("Receiver not registered")) {
                    LogUtils.e(TAG, "!!!!!!!!!!!!!!!!!ignore incorrect unregisterCheckNetwork!!!!!!!!!!!!!!!!!");
                    // Ignore this exception. This is exactly what is desired
                } else {
                    // unexpected, re-throw
                    throw e;
                }
            }
        }
    }

    class NetworkCheckReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                if (intent.getAction().equals(PlayerUtils.CONNECTIVTY_CHANGE)) {
                    if (updatePlayPageInWorkMobile()) {
                        if (mPlayMediaController != null && mPlayMediaController.mobileNetNeedPause()) { //在移动网络下需要暂停的情况
                            setPlayingProcess(true);
                            refreshToMobileNet();
                        } else {  //在移动网络下不需要暂停的情况
                            if (mPlayMediaController != null) {
                                setPlayingProcess(true);
                            }
                            refreshToMobileNet();
                        }
                    } else if (NetWorkTypeUtils.getNetType() == NetWorkTypeUtils.TYPE_ERROR ||
                            NetWorkTypeUtils.getNetType() == NetWorkTypeUtils.NETTYPE_NO) {
                        if(mPlayMediaController != null) {
                            mPlayMediaController.mobileNetNeedPause();
                        }
                        if (mPlayMediaController != null) {
                            setPlayingProcess(true);
                        }
                        reFreshToNoNet();
                    } else {
                        resumePlay();
                    }
                }
                if (intent.getAction().equals(Utils.SDCARD_NOSPACE_ACTION)) {
                    DialogUtil.getInstance(MoviesApplication.getInstance().getActivity()).checkSDCardSpaceDialog();
                }
                // 读取保存的之前网络状态
                SharedPreferences priorNetState = MoviesApplication.getInstance()
                        .getSharedPreferences("priornetstate", Activity.MODE_PRIVATE);
                int priorNetType = priorNetState.getInt("netstate", 2);
                int nowNetType = NetWorkTypeUtils.checkNet(intent, priorNetType);
                Editor editor = priorNetState.edit();
                editor.putInt("netstate", nowNetType);
                editor.commit();
            }
        }
    }

    public String getShareLink() {
        return video == null ? "" : video.getShareLink();
    }

    public Map<String, String> getShareDBMap() {
        return video == null ? null : BigDataApi.createDataMap("4", "", "0", video.getCategory(), video.getAid(), "-");
    }

    /**
     * 展现分享引导页面逻辑 zhangshuo 2014年12月8日 下午2:39:44
     */
    private void showShareGuidePage() {
        boolean flag = SharePreferenceManager.getVaule(this,
                SharePreferenceManager.SHARE_GUIDE_FLAG);
        if (!flag) {
            mShareGuideView = (RelativeLayout) findViewById(R.id.guide_share_view);
            mShareGuideView.setVisibility(View.VISIBLE);
            mShareGuideView.setOnTouchListener(new MyTouchListener());
            // 展现后设置标志为true
            SharePreferenceManager.saveVaule(this,
                    SharePreferenceManager.SHARE_GUIDE_FLAG, true);
            mHander.sendEmptyMessageDelayed(DISSMISS_SHAREGUIDE_PAGE,
                    SHAREGUIDE_DISSMISS_TIME);
        }
    }

    private class MyTouchListener implements OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (v.getId()) {
                case R.id.guide_share_view:
                    if (!isShareGuideGone && null != mShareGuideView
                            && mShareGuideView.isShown()) {
                        dismissShareGuide();
                    }
                    return true;
                default:
                    return false;
            }
        }
    }

    private void dismissShareGuide() {
        Animation animation = AnimationUtils.loadAnimation(
                VideoDetailActivity.this, R.anim.shareguidealpha);
        animation.setAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                isShareGuideGone = true;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mShareGuideView.setVisibility(View.GONE);
                isShareGuideGone = false;
            }
        });
        if (mShareGuideView.isShown()) {
            mShareGuideView.startAnimation(animation);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (null != mShareGuideView && mShareGuideView.isShown()) {
                    dismissShareGuide();
                } else if (!mIsHalfScreen) {
                    setOrientation(false);
                    setFullScreen(false, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else if (dismissAllPopWindow()) {
                } else {
                    MoviesApplication.getInstance().startMainFromPushBack(mCurActivity, null);
                    exitPlay();
                }
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private Handler mHander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == DISSMISS_SHAREGUIDE_PAGE) {
                dismissShareGuide();
            }
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        if (mPlayMediaController != null) {
            mPlayMediaController.LetvPlayerStatistics(Constants.LETV_PLAY_ACT_ON_STOP);
        }
        if(mBaiduAd != null){
            EventBus.getDefault().unregister(mBaiduAd);
        }
        if (!Utils.isAppOnForeground(getApplicationContext())) {
            isBackToForeGround = true;
        }
    }

    public PlayRecord getPlayRecord() {
        return playRecord;
    }

    private void requestAdData() {
        if (mDetailAdData == null) {
            mAdRequestResultListener = new AdRequestResultListener();
            mRequestAdTask = new RequestAdTask(MoviesApplication.getInstance(), MoviesHttpApi.DETAIL, mAdRequestResultListener);
            mRequestAdTask.start();
            LogUtils.e(TAG, "request addata !!!!end!!!!");
        } else {
            showAd();
        }
    }

    /**
     * 请求推荐列表位广告
     * @param recomPos recom1 or recom2
     */
    private void requestAdRecomByPos(String recomPos) {
        if (!NetWorkTypeUtils.isNetAvailable()) {
            return;
        }
        NewAdDataBean bean = null;
        if (SelfDataConstant.AD_PO_RECOM1.equals(recomPos)) {
            bean = beanRecomFirst;
        } else if (SelfDataConstant.AD_PO_RECOM2.equals(recomPos)) {
            bean = beanRecomSecond;
        }
        if (bean == null || Utils.TT_AD.equals(bean.provider)) {
            mAdRecomRequestResultListener = new AdRecomRequestResultListener(recomPos);
            mRequestAdRecomTask = new RequestAdTask(MoviesApplication.getInstance(), recomPos, mAdRecomRequestResultListener);
            mRequestAdRecomTask.start();
        } else {
            showAdRecom(bean,recomPos,true);
        }

    }

    private class AdRequestResultListener implements RequestResultListener<NewAdDataBean> {

        @Override
        public boolean onRequestFailed() {
            LogUtils.e(TAG, "!!!!!!!!!!!!!!请求广告数据失败!!!!!!!!!!!!!!");
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, NewAdDataBean result) {
            LogUtils.e(TAG, "!!!!!!!!!!!!!!AdDataBean：" + result);
            if (result != null) {
                AdRequestStatis.selfResponseReport(result, SelfDataConstant.AD_PO_DETAIL);
                LogUtils.e(TAG, "!!!!请求广告数据成功!!!!");
                mDetailAdData = result;
                showAd();
            }
        }

        @Override
        public void onPreRequest() {
        }
    }

    private void showAd() {
        if (mDetailAdData == null) {
            return;
        }
        Payload payload = mDetailAdData.payload;
        if (null == payload) {
            return;
        }
        lineAdTop.setVisibility(View.GONE);
        if (mDetailAdData.provider.equals(Utils.YZ_AD)) {
            YzPayAdView yzAdView = new YzPayAdView(this, "detail_one");
            yzAdView.setYzAd(((YzPayload) payload).ad);
        } else if (mDetailAdData.provider.equals(Utils.HZ_AD)) {
            HzPayAdView hzAdView = new HzPayAdView(this, "detail_one");
            hzAdView.setHzAd(((HzPayload) payload).ad);
        } else if (mDetailAdData.provider.equals(Utils.BAIDU_AD)) {
            mBaiduAd = new BaiduNativeAdView(this, "detail_one");
            EventBus.getDefault().register(mBaiduAd);
            mBaiduAd.setBaiduAd(((SDKPayload) payload).adId);
        } else if (mDetailAdData.provider.equals(Utils.GDT_AD)) {
            GdtNativeAdView gdtAd = new GdtNativeAdView(this, "one", "detail_one");
            gdtAd.loadAD(((SDKPayload) payload).adId);
        } else if (mDetailAdData.provider.equals(Utils.SERVER_AD)) {
            ServerNativeAdView serverAd = new ServerNativeAdView(this, "detail_one");
            ServerPayload serverPayload = (ServerPayload) payload;
            serverAd.setServerAd(serverPayload, MoviesHttpApi.DETAIL);
        } else if (mDetailAdData.provider.equals(Utils.XF_AD)) {
            XfPayAdView xfAdView = new XfPayAdView(this, "detail_one");
            xfAdView.setXfAd(((XfPayload) payload).ad);
        } else if (mDetailAdData.provider.equals(Utils.TT_AD)) {
            TtPayAdView ttAdView = new TtPayAdView(this, "detail_one");
            ttAdView.setTtAd(((TtPayload) payload).ad);
        }
    }

    private class AdRecomRequestResultListener implements RequestResultListener<NewAdDataBean> {

        private String mRecomPos;

        /**
         *
         * @param recomPos 位置 recom1 or recom2
         */
        public AdRecomRequestResultListener(String recomPos) {
            this.mRecomPos = recomPos;
        }


        @Override
        public boolean onRequestFailed() {
            if (mRecomPos.equals(SelfDataConstant.AD_PO_RECOM2)) {
                return false;
            }
            if (mRelativeList != null && mRelativeList.size() >= 20) {
                requestAdRecomByPos(SelfDataConstant.AD_PO_RECOM2);
            }
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, NewAdDataBean result) {
            if (result != null) {
                AdRequestStatis.selfResponseReport(result, mRecomPos);
                if (mRecomPos.equals(SelfDataConstant.AD_PO_RECOM1)) {
                    if (beanRecomFirst != null) {
                        showAdRecom(result,mRecomPos,true);
                    } else {
                        showAdRecom(result,mRecomPos,false);
                    }
                    beanRecomFirst = result;
                } else if (mRecomPos.equals(SelfDataConstant.AD_PO_RECOM2)) {
                    if (beanRecomSecond != null) {
                        showAdRecom(result,mRecomPos,true);
                    } else {
                        showAdRecom(result,mRecomPos,false);
                    }
                    beanRecomSecond = result;
                }
            }

        }

        @Override
        public void onPreRequest() {
        }
    }

    /**
     * 展示推荐列表位广告
     * @param recomPos 位置类型 recom1 or recom2
     */
    public void showAdRecom(NewAdDataBean dataBean,String recomPos,boolean isRemove) {
        if (dataBean == null || dataBean.ext == null || dataBean.payload == null ||
                mRelativeAdapter == null && mRelativeList == null ) {
            return;
        }
        int pos = dataBean.ext.pos;
        String adType = dataBean.provider;
        if (isRemove) {
            // 更新数据
            mRelativeAdapter.setRecomBean(dataBean, recomPos);
            mRelativeAdapter.notifyItemChanged(pos);
        } else {
            // 插入数据
            if (!TextUtils.isEmpty(adType)) {
                mRelativeAdapter.setRecomBean(dataBean, recomPos);
                mRelativeList.add(pos, null);
                mRelativeAdapter.notifyItemInserted(pos);
            }
        }

        // 加载下一个广告位
        if (!recomPos.equals(SelfDataConstant.AD_PO_RECOM2)) {
            if (mRelativeList != null && mRelativeList.size() >= 20) {
                requestAdRecomByPos(SelfDataConstant.AD_PO_RECOM2);
            }
        }

    }


    public class DetailRelativeMovieTask implements RequestResultListener<RelationList> {
        private RequestRelationsTask mRequestTask;

        public DetailRelativeMovieTask() {
            mRequestTask = new RequestRelationsTask(MoviesApplication.getInstance());
            String src = video.getSrc();
            String cid = video.getVt();
            String aid = video.getAid();
            mRequestTask.setParams(src, aid, cid);
            mRequestTask.setListener(this);
            mRequestTask.start();
        }

        @Override
        public boolean onRequestFailed() {
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, RelationList result) {
            if (result == null || result.isEmpty()) {
                relativeRecommendLl.setVisibility(View.GONE);
                lineRelativeTop.setVisibility(View.GONE);
            } else {
                if (episodeDataLl.getVisibility() == View.GONE) {
                    // 隐藏线
                    lineRelativeTop.setVisibility(View.GONE);
                } else {
                    // 显示线
                    lineRelativeTop.setVisibility(View.VISIBLE);
                }
                mRelativeList = result;
                relativeRecommendLl.setVisibility(View.VISIBLE);
                mRelativeAdapter = new RelativeListAdapter(VideoDetailActivity.this, mRelativeList, VideoDetailActivity.this);
                relativeListview.setAdapter(mRelativeAdapter);
                scrollView.scrollTo(0, 0);
                // 请求相关推荐广告,每10条一个广告位
                isFirstRequestRecomAd = true;
                requestAdRecom();
            }
        }

        @Override
        public void onPreRequest() {

        }

        private void cancel() {
            if (mRequestTask != null && !mRequestTask.isCancelled()) {
                mRequestTask.setListener(null);
                mRequestTask.cancel();
                mRequestTask = null;
            }
        }
    }

    /**
     * 请求推荐列表中的广告
     */
    private void requestAdRecom() {
        if (mRelativeList == null || mRelativeList.size() < 10) {
            return;
        }
        if (mRelativeList.size() >= 10) {
            requestAdRecomByPos(SelfDataConstant.AD_PO_RECOM1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private void showDialogBg(PopupWindow dialog) {
        mCurrentPopup = dialog;
        UIs.showOrHideBg(dialogBgRl, true);
    }

    private void showDialogBg(RelativeLayout vs) {
        mRelativeLayout = vs;
        UIs.showOrHideBg(dialogBgRl, true);
    }

    private void showDownloadMovePop() {
        updateDownloadedEpisodesNum(downLoadManager);
        if (Build.VERSION.SDK_INT < 24) {
            mDownloadPopup.showAsDropDown(mActionView, 0, UIs.dipToPx(220));
        } else {
            int[] location = new int[2];
            // 获取控件在屏幕的位置
            mActionView.getLocationOnScreen(location);
            mDownloadPopup.showAtLocation(mActionView, Gravity.NO_GRAVITY, 0, location[1] + mActionView.getHeight() + UIs.dipToPx(220));
        }
        showDialogBg(mDownloadPopup);
    }

    private void updateDownloadedEpisodesNum(DownloadManager manager) {
        if (getCurrentShowingEpisodeDownLoadAdapter() != null) {
            getCurrentShowingEpisodeDownLoadAdapter().updateDownloadedFlagByDB();
        }
        if (downloadedNumTv != null && manager != null) {
            ArrayList<DownloadJob> jobsList = manager.getProvider().getQueuedDownloads();
            if (jobsList != null && jobsList.size() > 0) {
                downloadedNumTv.setText(jobsList.size() > 99 ? "···" : jobsList.size() + "");
                downloadedNumTv.setVisibility(View.VISIBLE);
                downloadedNumMovTv.setText(jobsList.size() > 99 ? "···" : jobsList.size() + "");
                downloadedNumMovTv.setVisibility(View.VISIBLE);
            } else {
                downloadedNumTv.setVisibility(View.GONE);
                downloadedNumMovTv.setVisibility(View.GONE);
            }
        }
    }

    private void initMovieClarityUI() {
        setSingleClarity(mDefinition_fluency);
        setSingleClarity(mDefinition_common);
        setSingleClarity(mDefinition_highclear);
        setSingleClarity(mDefinition_super);
        setSingleClarity(mMoveDefinition_fluency);
        setSingleClarity(mMoveDefinition_common);
        setSingleClarity(mMoveDefinition_highclear);
        setSingleClarity(mMoveDefinition_super);
    }

    private void setSingleClarity(TextView tv) {
        tv.setBackgroundColor(getResources().getColor(R.color.white));
        tv.setTextColor(getResources().getColor(R.color.color_ff333333));
    }


    private String getmCrrentSite() {
        if (!TextUtils.isEmpty(mCurrentSite)) {

        } else {
            if (video != null) {
                PlaySrcList siteList = video.getSrcList();
                if (null != siteList && null != siteList.getPlaySrcList() && !siteList.getPlaySrcList().isEmpty())
                    mCurrentSite = (playRecord == null || TextUtils.isEmpty(playRecord.getSite())) ? siteList.getPlaySrcList().get(0).getSite() :
                            playRecord.getSite();
                if (siteList != null && siteList.getPlaySrcList() != null) {
                    ArrayList<String> siteStrList = new ArrayList<String>();
                    for (int i = 0; i < siteList.getPlaySrcList().size(); i++) {
                        siteStrList.add(siteList.getPlaySrcList().get(i).getSite());
                    }
                    mCurrentSite = siteStrList.contains(mCurrentSite) ? mCurrentSite : siteList.getPlaySrcList().get(0).getSite();
                }

            }
        }
        return mCurrentSite;
    }

    private String getmCurrentSiteName() {
        String site = getmCrrentSite();
        if (TextUtils.isEmpty(site)) {
            return null;
        }
        if (video != null && video.getSrcList() != null && video.getSrcList().getPlaySrcList() != null) {
            List<PlaySrcBean> playSrcList = video.getSrcList().getPlaySrcList();
            if (playSrcList.size() > 0) {
                for (PlaySrcBean playSrcBean : playSrcList) {
                    if (playSrcBean.getSite().equals(site)) {
                        return playSrcBean.getSitename();
                    }
                }
            }
        }
        return null;
    }

    Handler mHandler = new Handler();

    @Override
    public void onDownloadChanged(DownloadManager manager) {
//        mHandler.post(new Runnable() {
//            @Override
//            public void run() {
//                updateDownloadedEpisodesNum(downLoadManager);
//            }
//        });
    }

    @Override
    public void onDownloadEnd(DownloadManager manager) {

    }

    @Override
    public void dealWithUmeng() {
    }

    @Override
    public void dealWithVisitUmeng() {
        if (mHander == null) {
            return;
        }
        mHander.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(videoTitle) && video != null && !TextUtils.isEmpty(video.getCategoryname())) {
                    UmengEventPoster.postVideoDetailVisitTime(videoTitle, mLastFromClass, video.getCategoryname());
                }
            }
        }, 3000);
    }


    private void doDownLoad() {
        if (video != null) {
            if ("0".equals(mIsDownload)/* || TextUtils.isEmpty(mIsDownload)*/) {
                ToastUtil.showShortToast(
                        MoviesApplication.getInstance(),
                        R.string.can_not_download);
                return;
            }
            if (video.getVt().equals(MoviesConstant.VT_MOVIE)) {
                mDownloadPopup.setContentView(downloadPopupMoveView);
                if (mSizeManager.getFreeSize() > Utils.SDCARD_MINSIZE) {// sd卡容量大于100m，可以添加
                    ArrayList<Episode> episodeList = video.getEpisodeList();
                    //增加一个判断，处理umeng上的崩溃
                    if (episodeList != null && episodeList.size() > 0) {
                        Episode episode = episodeList.get(0);
                        if (downLoadManager.selectDownloadJobByMid(episode
                                .getSerialid())) {
                            ToastUtil.showShortToast(
                                    MoviesApplication.getInstance(),
                                    R.string.down_exists);
                        } else {
                            String time = "" + System.currentTimeMillis();// 时间戳，记录点击时间，在下载中界面排序
                            String temp = time.substring(2); // 去掉前两位
                            addTime = Integer.parseInt(1 + temp.substring(
                                    2, temp.length()));// 去掉最后一位
                            LogUtils.i("dyf", "" + time);
                            LogUtils.d("dyf", "" + addTime);
                            if ("letv".equals(video.getSubsrc()) && 0 == MoviesConstant.letvPlayStatus) {
                                defaultClarity(DefinitionManager.getSupportDefFlag(Arrays.asList(video.getEpisodeList().get(0).getPls().split(","))));
                                initClarityUI(true);
                                showDownloadMovePop();
                            } else if ("nets".equals(video.getSubsrc())) {
                                // 判断是否允许3g下载
                                if (NetWorkTypeUtils
                                        .reportNetType(VideoDetailActivity.this) == 2
                                        && !IsDownloadcan3g()) {
                                    checkIfContinueDownloadDialog(0, null,
                                            video.getAid(), episode,
                                            video.getSubsrc(), addTime);
                                } else {
//                                    updateAddedDownloadItem(0, null,
//                                            video.getAid(), episode,
//                                            video.getSubsrc(), addTime);
//                                    bdDownloadDataMap = BigDataApi.createDataMap("2", "", "0", video.getCategory(), video.getAid(), episode.getGlobaVid());
//                                    confirmDownload(0);
                                    initClarityNetUI();
                                    showDownloadMovePop();
                                }
                                CloudDownloadReport();
                            } else if (DownloadUtils.ISDOWNLOAD.equals(episode.getIsdownload())) {
                                defaultClarity(null);
                                initOutSiteClarityUI();
                                showDownloadMovePop();
                            } else {
                                ToastUtil.showShortToast(
                                        MoviesApplication.getInstance(),
                                        R.string.addfailure);
                            }
                        }
                    } else {
                        ToastUtil.showShortToast(VideoDetailActivity.this,
                                R.string.no_downloaddata_txt);
                    }
                } else {
                    ToastUtil.showShortToast(VideoDetailActivity.this,
                            R.string.sdcard_nospace);
                }

            } else {
                if ("nets".equalsIgnoreCase(video.getSubsrc())) {
                    initClarityNetUI();
                } else if ("letv".equalsIgnoreCase(video.getSubsrc()) && 0 == MoviesConstant.letvPlayStatus) {
                    defaultClarity(DefinitionManager.getSupportDefFlag(Arrays.asList(video.getEpisodeList().get(0).getPls().split(","))));
                    initClarityUI(true);
                } else {
                    defaultClarity(null);
                    initOutSiteClarityUI();
                }
                showDownloadEpisodesPop();
            }
        }
    }

    /**
     * 下载弹层 针对电影的
     */
    private void initDownloadMoveView() {
        downloadPopupMoveView = View.inflate(this, R.layout.popup_move_download_layout, null);
        mMoveDefinition_fluency = (TextView) downloadPopupMoveView.findViewById(R.id.definition_fluency_tv);
        mMoveDefinition_common = (TextView) downloadPopupMoveView.findViewById(R.id.definition_common_tv);
        mMoveDefinition_highclear = (TextView) downloadPopupMoveView.findViewById(R.id.definition_highclear_tv);
        mMoveDefinition_super = (TextView) downloadPopupMoveView.findViewById(R.id.definition_super_tv);
        downloadedNumMovTv = (TextView) downloadPopupMoveView.findViewById(R.id.download_num_tv);
        mMoveDefinition_fluency.setOnClickListener(clarityClickListener);
        mMoveDefinition_common.setOnClickListener(clarityClickListener);
        mMoveDefinition_highclear.setOnClickListener(clarityClickListener);
        mMoveDefinition_super.setOnClickListener(clarityClickListener);
        ImageView cancelIv = (ImageView) downloadPopupMoveView.findViewById(R.id.iv_close);
        cancelIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mDownloadPopup.dismiss();
                UIs.showOrHideBg(dialogBgRl, false);
            }
        });
        TextView rightTv = (TextView) downloadPopupMoveView.findViewById(R.id.right_tv);
        rightTv.setText(R.string.download_manager_list);
        rightTv.setVisibility(View.VISIBLE);
        downloadPopupMoveView.findViewById(R.id.bottom_lay).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(VideoDetailActivity.this,
                        DownloadActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 控制清晰度UI
     */
    private void initClarityNetUI() {
        if (video.getEpisodeList() == null || video.getEpisodeList().size() < 1) {
            return;
        }
        Episode ep = null;
        if (video.getEpisodeList().size() > 0) {
            ep = video.getEpisodeList().get(0);
        }

        if (MoviesConstant.VT_MOVIE.equals(video.getVt())) {
            initMovieClarityUI();
        }
        if (null != ep && !TextUtils.isEmpty(ep.getPls())) {
            Map<String, Boolean> mClaritymap = mPlayMediaController.getmClaritymap();
            if (null != mClaritymap && mClaritymap.size() > 0) {
                if (MoviesConstant.VT_MOVIE.equals(video.getVt())) {
                    if ("nets".equals(video.getSubsrc())) {
                        setClarityText(mMoveDefinition_super, DefinitionManager.DEFINITION_TYPE_SUPER.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_SUPER));
                        setClarityText(mMoveDefinition_highclear, DefinitionManager.DEFINITION_TYPE_HIGH.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_HIGH));
                        setClarityText(mMoveDefinition_common, DefinitionManager.DEFINITION_TYPE_NORMAL.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_NORMAL));
                        setClarityText(mMoveDefinition_fluency, DefinitionManager.DEFINITION_TYPE_FLUENCY.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_FLUENCY));
                    }
                } else {
                    if ("nets".equals(video.getSubsrc())) {
                        setClarityText(mDefinition_super, DefinitionManager.DEFINITION_TYPE_SUPER.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_SUPER));
                        setClarityText(mDefinition_highclear, DefinitionManager.DEFINITION_TYPE_HIGH.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_HIGH));
                        setClarityText(mDefinition_common, DefinitionManager.DEFINITION_TYPE_NORMAL.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_NORMAL));
                        setClarityText(mDefinition_fluency, DefinitionManager.DEFINITION_TYPE_FLUENCY.equals(mdefaultClarity), mClaritymap.get(DefinitionManager.DEFINITION_TYPE_FLUENCY));
                    }
                }
            }
        }

    }

    private void setClarityText(TextView tv, boolean isCurrentClarity, boolean isEable) {
        if (isEable) {
            if (isCurrentClarity) {
                tv.setTextColor(getResources().getColor(R.color.color_3599f8));
                tv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            } else {
                tv.setTextColor(getResources().getColor(R.color.color_ff333333));
                tv.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            }
            tv.setClickable(true);
        } else {
            tv.setClickable(false);
            tv.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            tv.setTextColor(getResources().getColor(
                    R.color.color_d2d2d2));// 不可用
        }
    }

    @Override
    public void loadNetClarityComplete(ArrayList<String> videoCaseList) {
        if (videoCaseList != null && videoCaseList.size() > 0) {
            mDownloadImage.setVisibility(View.VISIBLE);
            mDownloadImage.setImageResource(R.drawable.download_icon);
            mDownloadImage.setClickable(true);
            defaultClarity(mPlayMediaController.getmClaritymap());
        } else {
            mDownloadImage.setVisibility(View.GONE);
        }

    }

    /**
     * 判断默认清晰度
     */
    private void defaultClarity(Map<String, Boolean> mClaritymap) {
        // 当前需要获取的视频编码格式,先查找标清片源是否存在查找兼容片源是否存在
        String mClaritySetting = getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE, Context.MODE_PRIVATE).getString(MoviesConstant.DOWNLOAD_SHARPNESS_SELECT, MoviesConstant.SUPER);
        if (DefinitionManager.isDefinitionFluency(mClaritySetting)) {
            if (mClaritymap != null)
                mdefaultClarity = mClaritymap.get(DefinitionManager.DEFINITION_TYPE_FLUENCY) ? DefinitionManager.DEFINITION_TYPE_FLUENCY :
                        mClaritymap.get(DefinitionManager.DEFINITION_TYPE_NORMAL) ? DefinitionManager.DEFINITION_TYPE_NORMAL :
                                mClaritymap.get(DefinitionManager.DEFINITION_TYPE_HIGH) ? DefinitionManager.DEFINITION_TYPE_HIGH : DefinitionManager.DEFINITION_TYPE_SUPER;
            mOutsiteClarity = MoviesConstant.NORMAL;
        } else if (DefinitionManager.isDefinitionNormal(mClaritySetting)) {
            if (mClaritymap != null)
                mdefaultClarity = mClaritymap.get(DefinitionManager.DEFINITION_TYPE_NORMAL) ? DefinitionManager.DEFINITION_TYPE_NORMAL :
                        mClaritymap.get(DefinitionManager.DEFINITION_TYPE_FLUENCY) ? DefinitionManager.DEFINITION_TYPE_FLUENCY :
                                mClaritymap.get(DefinitionManager.DEFINITION_TYPE_HIGH) ? DefinitionManager.DEFINITION_TYPE_HIGH : DefinitionManager.DEFINITION_TYPE_SUPER;
            mOutsiteClarity = MoviesConstant.HIGH;
        } else if (DefinitionManager.isDefinitionHigh(mClaritySetting)) {
            if (mClaritymap != null)
                mdefaultClarity = mClaritymap.get(DefinitionManager.DEFINITION_TYPE_HIGH) ? DefinitionManager.DEFINITION_TYPE_HIGH :
                        mClaritymap.get(DefinitionManager.DEFINITION_TYPE_NORMAL) ? DefinitionManager.DEFINITION_TYPE_NORMAL :
                                mClaritymap.get(DefinitionManager.DEFINITION_TYPE_SUPER) ? DefinitionManager.DEFINITION_TYPE_SUPER : DefinitionManager.DEFINITION_TYPE_FLUENCY;
            mOutsiteClarity = MoviesConstant.SUPER;
        } else if (DefinitionManager.isDefinitionSuper(mClaritySetting)) {
            if (mClaritymap != null)
                mdefaultClarity = mClaritymap.get(DefinitionManager.DEFINITION_TYPE_SUPER) ? DefinitionManager.DEFINITION_TYPE_SUPER :
                        mClaritymap.get(DefinitionManager.DEFINITION_TYPE_HIGH) ? DefinitionManager.DEFINITION_TYPE_HIGH :
                                mClaritymap.get(DefinitionManager.DEFINITION_TYPE_NORMAL) ? DefinitionManager.DEFINITION_TYPE_NORMAL : DefinitionManager.DEFINITION_TYPE_FLUENCY;
            mOutsiteClarity = MoviesConstant.SUPER2;
        }
    }

    private void showDownloadEpisodesPop() {
        UmengEventPoster.doEventPost("download_detail_show");
        mDownLoadRelativeLayout.setVisibility(View.VISIBLE);
        setClickable(false);
        mDownLoadRelativeLayout.setAnimation(AnimationUtils.loadAnimation(this, R.anim.dialog_push_in));
        if (getCurrentShowingEpisodeDownLoadAdapter() != null) {
            getCurrentShowingEpisodeDownLoadAdapter().setmSelectProder(currentPlayingPorder());
            getCurrentShowingEpisodeDownLoadAdapter().updateDownloadedFlagByDB();
        }
    }

    /**
     * 下载
     * @param view
     * @param position
     */
    public void downLoadEpisodes(View view, int position) {
        {
            if (mSizeManager.getFreeSize() > Utils.SDCARD_MINSIZE) {//sd卡容量大于100m，可以添加
                String time = "" + System.currentTimeMillis();//时间戳，记录点击时间，在下载中界面排序
                String temp = time.substring(2); //去掉前两位
                int addTime = Integer.parseInt(1 + temp.substring(2, temp.length()));//去掉最后一位
                boolean ifDownload = false;
                if (null != mDownLoadCurrentEpisodePlayAdapter && video.getEpisodeList().size() > position) {// 电视剧卡通类型此条件成立
                    Episode ep = video.getEpisodeList().get(position);
                    if (null == ep)
                        return;
                    if ((DownloadUtils.ISDOWNLOAD.equals(ep.getIsdownload()))) {
                        ifDownload = true;
                    } else {
                        ifDownload = false;
                    }

                    if (ifDownload) {
                        //判断是否允许3g下载
                        if (NetWorkTypeUtils.reportNetType(VideoDetailActivity.this) == 2 && !IsDownloadcan3g()) {
                            checkIfContinueDownloadDialog(position, null, video.getAid(), ep, video.getSubsrc(), addTime);
                        } else {
                            updateAddedDownloadItem(position, null, video.getAid(), ep, video.getSubsrc(), addTime);
                            bdDownloadDataMap = BigDataApi.createDataMap("2", "", "0", video.getCategory(), video.getAid(), ep.getGlobaVid());
                            confirmDownload(position);
                        }
                    } else {
                        ToastUtil.showShortToast(MoviesApplication.getInstance(), R.string.addfailure);
                    }
                }
                if (null != mDownLoadCurrentEpisodePlayAdapter && ifDownload) {// 电视剧卡通类型此条件成立
//                    mDownLoadCurrentEpisodePlayAdapter.setSelectedItem(position, view);
                }

            } else {
                ToastUtil.showShortToast(VideoDetailActivity.this, R.string.sdcard_nospace);
            }
        }
        view.postDelayed(new Runnable() {
            @Override
            public void run() {
                PlayerUtils.sendPlayingBroadcast(VideoDetailActivity.this);
            }
        }, 2000);
    }

    private void changePlaySrc(int pos) {
        PlaySrcBean playsrc = popupAdapter.getPlaySrcList().getPlaySrcList().get(pos);

        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
        String siteName = playsrc.getSite();
        if (requestPlaySrcDetail != null) {
            requestPlaySrcDetail.cancel();
        }
        mCurrentSite = siteName;
        if (null != mPlayMediaController) {
            mPlayMediaController.onPause();
            mPlayMediaController.setControllerUI();
        }
        requestPlaySrcDetail = new RequestPlaySrcDetailTask(MoviesApplication.getInstance(), siteName);
        requestPlaySrcDetail.start();
        if (popupAdapter != null) {
            popupAdapter.setSelectPosition(playsrc.getSite());
        }
        // 播放源点击友盟统计
        UmengEventPoster.postWebSiteClick(siteName);
    }

}
